JS truncates the decimal point to avoid floating point problems

The commonly used JS truncation method found on the Internet will cause bugs when encountering relatively special numbers, mainly because of JS floating point calculation problems.

Commonly used JS truncated decimal point methods are as follows:

function pointNumber(number,length) {
    return Math.floor(number*Math.pow(10,length))/Math.pow(10,length)
}

But this pointNumber(522.18,3) returns 522.179 instead of 522.18,
Insert picture description here
but the following method can better avoid floating-point calculation problems.

function fixNumber(number = 0,numLength = 4) {
    let length = number.toString()
    let num = '0.'
    if (length.indexOf('.') == -1) {
        return number
    }
    length = length.split('.')[1].length < numLength ? numLength : length.split('.')[1].length
    for (var i=0; i<length; i++) {
        num += '0'
    }
    num += '1'
    return Math.floor((Number(number) + Number(num)) * Math.pow(10,numLength)) / Math.pow(10,numLength)
}

The result of the operation is as shown in the figure below. The decimal point is perfectly truncated and there is no floating point problem.
Insert picture description here

Tips: I have tested some of them and there is no problem. If you find any problems, please contact me. This method is also used in my own projects.

Guess you like

Origin blog.csdn.net/weixin_43968658/article/details/103261467