如何解决我的replace方法弄乱了数字格式在num中添加逗号
一切都很好,直到达到6,555,444,333,222,111或说四倍,在我再加上一个数字(任意数字)之后,它变成65,554,443,332,220(例如,数字为5,它将自动为0,即其中的任何数字都将替换为0) 因为我在制作计算器,所以如果它是6兆,并且我按了按钮2例如,最后一个值应该是2,但显示为0。
这里是我的代码:
ListView {
id: listId
MouseArea {
anchors.fill: parent
onClicked: {
boxId.visible = false
} //unable to use 'boxId' like this. Getting reference error
}
delegate: Rectangle {}
highlight: Rectangle {
id: boxId
}
}
Number.prototype.formattedNumber = function() {
this.Number = String(this).split('\.'); //Split '.' So it doesnt affect decimals
if(this.Number.length > 1) {
this.first = this.Number[0];
this.second = this.Number[1];
this.Number = this.first.replace(/(\d)(?=(\d{3})+(?!\d))/g,'$1,') + '.' + this.second;
return this.Number;
}else{
this.first = this.Number[0];
this.Number = this.first.replace(/(\d)(?=(\d{3})+(?!\d))/g,');
console.log(this.Number);
return this.Number;
}
}
反正有解决此问题的方法吗?
解决方法
如果再加一个数字意味着多一个数字,那是因为您超出了javascript的最大安全整数值。有关更多信息,请参见MDN上的this page。
您以四位数表示的数字:6,555,444,333,222,111
javascript的最大安全整数值:9,007,199,254,740,991
彼此相邻:
6,111
9,991
在示例中再添加一个数字将使其比最大整数值大一个数量级,并且由于javascript不知道如何处理,因此最终会失去一些准确性。
您应该检查输入的数字,如果数字大于16,请使用BigInt。您可能还需要重做代码其他部分的工作,例如parseFloat在使用BigInt时会失去准确性,因为它试图将BigInt转换为Number。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。