Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits?

For example:

1 // acceptable
1.1 // acceptable
1.11 // acceptable
1.111 // not acceptable

Is there a method to achieve this? I checked Zod's documentation and searched online, but all the solutions seem to be for string properties, not numbers.

Answer №1

z.number().multipleOf(0.01)

can be a clever workaround (even for non-integer values!).

Yet, there's a concern about the IEEE 754 representation problem (it has its own term - though slipped my mind - and isn't exclusive to JS), as shown in this scenario:

z.number().multipleOf(0.01).parse(0.1 + 0.1 + 0.1)

This will throw an error due to the fact that 0.1 + 0.1 + 0.1 actually equals 0.300000000004 internally.

Perhaps using refine() along with a comparison against Number.EPSILON could offer a more dependable solution:

z.number()
  .refine(x => x * 100 - Math.trunc(x * 100)< Number.EPSILON)
  .parse(0.1 + 0.1  + 0.1) // should work fine

[upd] according to @captain-yossarianfromUkraine, Number.EPSILON might address float-number concerns

PS unable to compare this method with the usage of z.custom() suggested by @vera

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

Change the x and y positions of several div elements as the mouse moves in JavaScript

I am aiming to create a webpage where multiple divs with text and other content move along the x and y axes of the mouse. The desired effect is similar to parallax scrolling, but I have found that existing parallax plugins are image-based and do not work w ...

Are there any debugging tools specific to Internet Explorer for JavaScript?

I need a reliable JavaScript debugger for Internet Explorer. I have tried using Firebug Lite, but it doesn't seem as detailed as the original Firebug when it comes to displaying JavaScript errors. Does anyone know how to pinpoint JavaScript errors in ...

Selecting Content Dynamically with jQuery

I have a webpage with multiple dynamic content sections. <div id="content-1"> <div id="subcontent-1"></div> <i id="delete-1"></i> </div> . . . <div id="content-10"> <div id="subcontent-10"></d ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Using ng-repeat to iterate over forms in AngularJS

I have implemented dynamic forms using the ng-repeat directive where form fields are generated based on the userid value. The requirement is that the add user button should be enabled only when all form fields are filled. However, currently the button rema ...

Is it possible to pass multiple functions to the parent component in ReactJs if using OnChange() as a prop?

Just getting started with React and trying to pass data from a child component to a parent component. <div className="filter-module"> <i className="fas fa-sign-in-alt icon"></i> < ...

When it comes to JavaScript, the evaluation order of arguments and delayed evaluation play a crucial

Assuming function( arg1, arg2 ), is it true that arg1 will always evaluate before arg2 (unlike traditional C)? Is there a way to create a function where arguments are not evaluated immediately, but only on demand? For instance, in if( cond1 || cond2 ), c ...

What is the best way to ensure that my $.ajax POST call works seamlessly with SSL?

Below is the JavaScript code I am using: parameter = "name=" + name + "&email=" + email + "&phone=" + phone + "&comments=" + comments; $.ajax({ url: 'sendEmail.php?' + parameter, success: ...

Ways to activate the enter key

Here we have the input bar and search button setup in our HTML code: <div> <div class="input-group search-bar"> <input type="text" class="form-control search-box" placeholder="Search people" autofocus="" ng-model="searchPeople"& ...

Is it possible to globally delay the execution of WebElement.sendKeys() in Protractor's onPrepare function?

While running protractor on a sluggish machine, I am in need of slowing down each key press and action performed. The action part has been successfully implemented, but how can I achieve the same for key presses? I have come up with a local solution which ...

the session data is being mishandled

I have integrated express-session and express-mysql-session in my application to handle sessions and store them in a MySQL database. The session data is saved in a table named "sessions". const express = require('express'); const session = requir ...

What is the best way to utilize a union of interfaces in TypeScript when working with instances?

Review this TypeScript snippet: class A {public name: string = 'A';} interface B {num: number;} class Foo { get mixed(): Array<A | B> { const result = []; for (var i = 0; i < 100; i ++) { result.push(Mat ...

Maintaining the user interface state while utilizing $resources in AngularJS

For my app, users have the ability to create and delete items. I've implemented $resources for this functionality, which is working really well. However, I'd like to implement a loading screen that appears whenever a request is being processed. ...

Tips on hovering over information retrieved from JSON data

Within my code, I am extracting information from a JSON file and placing it inside a div: document.getElementById('display_area').innerHTML += "<p>" + jsonData[obj]["name"] + "</p>"; I would like the abi ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Is there a way to output several lines from a JSON file in print form?

I'm working with HTML code that displays multiple lines from a JSON file, but it only shows one line at a time. How can I modify the code to display all users' information? <!DOCTYPE html> <html> <head> <script> function ...

Issue with AngularJS controller method not functioning properly when assigned to a Div

I am facing an issue with a login form and its controller. The login function is not triggering upon submitting the form for some reason. Here is the code snippet for the form within the larger view file: <div class="login-wrap" ng-controller="LoginCt ...