Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to number but maintain zeros in Javascript

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?

like image 376
Mohammed Avatar asked Apr 07 '26 01:04

Mohammed


1 Answers

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));
like image 137
Mohsen Alyafei Avatar answered Apr 08 '26 16:04

Mohsen Alyafei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!