Home > other >  Convert string to number but maintain zeros in Javascript
Convert string to number but maintain zeros in Javascript

Time:03-14

I am working with GBP currency in Javascript and converting a string currency to a number like the following: Number('1.20') will give me 1.2. But I want to maintain the 0 when converting to a number type. Is this possible? This is the result that I want : 1.20. Can anyone help me please?

CodePudding user response:

You can control the decimals like this in Javascript:

let num = 1.204;
let n = num.toFixed(2)

CodePudding user response:

A better way to work with Currency in Javascript is to use the Intl.NumberFormat. For course, the output will be of the type: 'String'

The output will take care of the number of decimal places depending on the Currency you specify. In your case GBP so it will be 2 decimal places.

Example:

const number = 1.2;
console.log(new Intl.NumberFormat('en', { style: 'currency', currency: 'GBP' }).format(number));

  • Related