在JavaScript中将整数美分转换为可读的美元金额

Convert a whole number amount of cents to a readable dollar amount in JavaScript?

本文关键字:金额 美元 转换 JavaScript 整数      更新时间:2023-09-26
var num = 1629; // this represents $16.29
num.toLocaleString("en-US", {style:"currency", currency:"USD"});
// outputs $1,629

到目前为止,这是我能做到的最接近的了。我尝试了toLocaleString提供的所有选项,但似乎没有简单的方法来获得我想要的结果(这与预期不同)。有没有在JS中存在的内置函数?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

试着将美分数除以100得到等值的美元。例如:

const number = 1629;
const dollars = (cents / 100).toLocaleString("en-US", {style:"currency", currency:"USD"});

dollars现在等于"$16.29"

为什么不在toLocaleString之前除以100呢?

var num = 1629; // this represents $16.29
num /= 100; // cent to dollar
num.toLocaleString("en-US", {style:"currency", currency:"USD"});