我的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。