在 JavaScript 中将整数美分转换为可读的美元金额?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32768494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a whole number amount of cents to a readable dollar amount in JavaScript?
提问by whocodes
var num = 1629; // this represents .29
num.toLocaleString("en-US", {style:"currency", currency:"USD"});
// outputs ,629
So far this is as close as I can come. I tried all of the options that toLocaleString provides but there seems to be no easy way to get the outcome I want (which is not as expected). Is there no built-in function that exists in JS?
到目前为止,这是我所能接近的。我尝试了 toLocaleString 提供的所有选项,但似乎没有简单的方法来获得我想要的结果(这不是预期的)。JS中没有内置函数吗?
回答by amklose
Try dividing the number of cents by 100 to get the dollar equivalent. I.E.:
尝试将美分数除以 100 以获得等值的美元。IE:
var num = 1629;
var dollars = num / 100;
dollars = dollars.toLocaleString("en-US", {style:"currency", currency:"USD"});
dollars
now equals "$16.29"
dollars
现在等于“$16.29”
回答by ManzMoody
Why not divide through 100 before toLocaleString?
为什么不在 toLocaleString 之前除以 100?
var num = 1629; // this represents .29
num /= 100; // cent to dollar
num.toLocaleString("en-US", {style:"currency", currency:"USD"});