I have an integer stored as US cents, ie 1700 cents. How can I convert that to a string that is $17.00 using javascript? I have tried toFixed
and Intl.NumberFormat
but they return $1700?
I have an integer stored as US cents, ie 1700 cents. How can I convert that to a string that is $17.00 using javascript? I have tried toFixed
and Intl.NumberFormat
but they return $1700?
- Have you tried dividing the value by 100 first...? – user5734311 Commented May 15, 2022 at 10:41
-
Can you show the way in which you used
toFixed()
andIntl.numberFormat
? – David Thomas Commented May 15, 2022 at 10:41
3 Answers
Reset to default 5You can use toLocaleString()
function for this.
var cents = 1629;
var dollars = cents / 100;
dollars = dollars.toLocaleString("en-US", {style:"currency", currency:"USD"});
console.log(dollars);
Another solution could be this:
var cents = 1629
var currency = cents/100
console.log(new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(currency))
console.log(new Intl.NumberFormat('es-ES', { style: 'currency', currency: 'EUR' }).format(currency))
you can also try this simple javascript number format
const currencyConverter = (amount) => {
let dollars = amount/ 100;
const result = Number(dollars).toLocaleString("en-US");
return result;
}
now you have a reusable currency converter function which to use you just have to call and then pass the number into the function
currencyConverter(1700)