在我的数据库中,我存储没有任何点或逗号的货币值。 所以我需要一个 Javascript 函数将其转换为货币字符串。
示例:将 500(五美元)转换为 5.00、100 转换为 1.00、550 转换为 5.50 等
有人可以发布这样的函数吗?
最佳答案
你可以使用类似的东西:
function toAmount(amount){
amount = Number(amount);
if (isNaN(amount)){
throw 'invalid: can\'t convert input';
}
return (amount/100).toFixed(2);
}
//usage
toAmount(500); //=> 5.00
toAmount(520873); //=> 5208.73
toAmount('500'); //=> 5.00
或者使用该函数作为 Number
的扩展
Number.prototype.toAmount = function toAmount(amount){
return (this/100).toFixed(2);
};
//usage:
(500).toAmount(); //= 5.00
(520873).toAmount(); //=> 5208.73
关于Javascript:将整数转换为字符串(货币表示)的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9644878/