I have an object with a numeric property. I'd like to make sure that the number has only up to 2 decimal digit.
e.g:
1 // good 1.1 // good 1.11 // good 1.111 //bad
Is there way to do that?
Looked at Zod's documentation and searched the web. Found that i could have done it easily if my property was a string. Not sure about number.
I have an object with a numeric property. I'd like to make sure that the number has only up to 2 decimal digit.
e.g:
1 // good 1.1 // good 1.11 // good 1.111 //bad
Is there way to do that?
Looked at Zod's documentation and searched the web. Found that i could have done it easily if my property was a string. Not sure about number.
Share Improve this question asked Jan 30, 2023 at 13:37 UriUri 831 gold badge1 silver badge4 bronze badges 6-
THen just convert your nubmer to string
${number}
or number.toString() – captain-yossarian from Ukraine Commented Jan 30, 2023 at 13:53 - Tnx for answering @captain-yossarianfromUkraine. At my case i cannot convert the value as the validating is done in a generic layer, i need to define my requirement as a part of the object's schema. WDYT? – Uri Commented Jan 30, 2023 at 14:15
- 4 Using z.custom? – tenshi Commented Jan 30, 2023 at 14:50
- tnx @vera. do you think custom / refine are the right way to go here? was afraid that its a hack (?) – Uri Commented Jan 30, 2023 at 15:03
- 1 I don't see how else you're going to do it :p – tenshi Commented Jan 30, 2023 at 15:04
1 Answer
Reset to default 14z.number().multipleOf(0.01)
will do the hack(yes, it can work with non-integer too!).
However, I worry about IEEE 754 representation issue(it even has its own name - but I forgot - and is not specific to JS), when
z.number().multipleOf(0.01).parse(0.1 + 0.1 + 0.1)
will throw, since 0.1 + 0.1 + 0.1 under the hood bees 0.300000000004
Maybe refine()
will be more reliable with checking against Number.EPSILON
:
z.number()
.refine(x => x * 100 - Math.trunc(x * 100)< Number.EPSILON)
.parse(0.1 + 0.1 + 0.1) // ok
[upd] as @captain-yossarianfromUkraine noticed, Number.EPSILON should help with float-number thing
PS cannot evaluate this approach against z.custom()
proposed by @vera