3

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?

Andy
  • 61,948
  • 13
  • 68
  • 95
Mohammed
  • 555
  • 1
  • 6
  • 19
  • maintain how? where does the missing 0 cause issue? – depperm Mar 14 '22 at 12:40
  • 1
    It seems you are confusing number *values* with their *representation*. `1.2` and `1.20` are the same number *value*. If you need the trailing zero for *display* purposes then see [Formatting a number with exactly two decimals in JavaScript](https://stackoverflow.com/q/1726630/218196) – Felix Kling Mar 14 '22 at 12:41
  • 2
    Use [Intl.NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat) for currencies. – Lain Mar 14 '22 at 12:42
  • 1
    Both are the same numbers. Even if you use toFixed, it'll be converted to string & if you try to convert it to Number, it'll strip zero again. – Ali Demirci Mar 14 '22 at 12:43
  • No, this is not possible, numbers in JS are [IEEE754 floating-point numbers](https://en.wikipedia.org/wiki/IEEE_754), and the standard doesn't include leading or trailing zeros. – Teemu Mar 14 '22 at 12:50

2 Answers2

1

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));
Mohsen Alyafei
  • 4,765
  • 3
  • 30
  • 42
-1

You can control the decimals like this in Javascript:

let num = 1.204;
let n = num.toFixed(2)
Mihai Lupu
  • 67
  • 5