Next.js Discord

Discord Forum

Help with Yup validation for currency

Unanswered
Asiatic Lion posted this in #help-forum
Open in Discord
Asiatic LionOP
for next js i have been using Yup validation for currency (it's number not string value)

and this is my validation schema
    price: yup.number().required('Price is required')
        .test('is-decimal', 'Price should have at most 2 decimals.', (value) => {
            return Number.isInteger(Number(value) * 100);
        }),

but i get the floating issue for value 4.15

and if i did this
    price: yup.number().required('Price is required')
        .test('is-decimal', 'Price should have at most 2 decimals.', (value) => {
            const multiplied = Math.round(value * 100);
            return Math.abs(value * 100 - multiplied) < 1e-8;
            return Number.isInteger(Number(value) * 100);
        }),

i can enter this value in it
414.99999999999994

1 Reply

Scottish Fold
You’re running into floating point precision issues. Instead of checking with Number.isInteger(value * 100), use an epsilon comparison like this:

price: yup.number().required('Price is required')
.test('is-decimal', 'Price should have at most 2 decimals.', (value) => {
if (typeof value !== 'number') return false;
const scaled = value * 100;
return Math.abs(scaled - Math.round(scaled)) < 1e-8;
});