Is it possible to find a number of decimal digits for currency (e.g. 2 for USD, 0 for yen) in Javascript?
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
Is it possible to find a number of decimal digits for currency (e.g. 2 for USD, 0 for yen) in Javascript?
3
Answers
The number of decimal positions can be extracted using
Intl.NumberFormat#formatToParts()
. It returns an array of formatting.This can then be programmatically parsed to find
type: "fraction"
and retrieve its length. If no such part is found, then the length is zero:Depending on your applications here’s what I came up with. You might find more optimized solutions later.
I don’t know what format your number is in; more specifically if it is an actual number (123) or a string of a number ("123"), so I supported both.
The transInput variable takes the input to the function and converts it into a number if needed.
The first if statement checks to see if the converted number is an integer (a number without a decimal) as integers don’t have a decimal to check for. I did this by evaluating the number modulo 1, which is fancy math jargon for taking everything before the decimal out of the number. If this value is zero, the number did not have anything after the decimal, or no decimal at all.
If the aforementioned condition is false, the function knows there is a decimal, and will isolate the numbers after the decimal by converting the number back to a string, and splitting the string at the decimal point. All that is left is to find the length of the string with the numbers after the decimal.
I hope this helped!
Yes, you can find the number of decimal digits for a currency value in JavaScript.
This function takes a currency code as input and returns the corresponding number of decimal digits for that currency.