最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript How To Format An Integer As A Currency String? - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked May 15, 2022 at 10:37 summer9844summer9844 1852 silver badges16 bronze badges 2
  • 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() and Intl.numberFormat? – David Thomas Commented May 15, 2022 at 10:41
Add a ment  | 

3 Answers 3

Reset to default 5

You 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)
发布评论

评论列表(0)

  1. 暂无评论