gpt4 book ai didi

javascript - 用负数格式化货币

转载 作者:行者123 更新时间:2023-11-30 08:51:50 24 4
gpt4 key购买 nike

我有一个 javascript 函数,可以很好地处理正数,但是当输入负数时,它会警告 NaN:

function formatMoney(number) {
number = parseFloat(number.toString().match(/^\d+\.?\d{0,2}/));
//Seperates the components of the number
var components = (Math.floor(number * 100) / 100).toString().split(".");
//Comma-fies the first part
components [0] = components [0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
//Combines the two sections
return components.join(".");
}
alert(formatMoney(-11));

这是jsFiddle中的例子 http://jsfiddle.net/longvu/wRYsU/

谢谢你的帮助

最佳答案

/^\d+\.?\d{0,2}/ 中不允许使用前导符号,它必须以数字开头。

第一步是允许这样做,比如:

/^-?\d+\.?\d{0,2}/

如果您将 that 放在您的示例 jsfiddle 脚本中,您会得到一个包含 -11 而不是 NaN 的对话框。

关于javascript - 用负数格式化货币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com