解决JS 计算精度问题

31 阅读1分钟
// 加法
function plus(num1,num2){
    var place1=place2=0
    try {
        place1= (num1+'').split('.')[1].length
    } catch (error) {}
    try {
        place2 += (num2+'').split('.')[1].length
    } catch (error) {}
    var place = Math.max(place1,place2)
    var number = num1 + num2
    return Math.round(number * Math.pow(10, place)) / Math.pow(10, place);
}

// 减法
function minus(num1,num2){
    var place1=place2=0
    try {
        place1= (num1+'').split('.')[1].length
    } catch (error) {}
    try {
        place2 += (num2+'').split('.')[1].length
    } catch (error) {}
    var place = Math.max(place1,place2)
    var number = num1 - num2
    return Math.round(number * Math.pow(10, place)) / Math.pow(10, place);
}

// 乘法
function times(num1,num2){
    var place=0
    try {
        place += (num1+'').split('.')[1].length
    } catch (error) {}
    try {
        place += (num2+'').split('.')[1].length
    } catch (error) {}
    var number = num1 * num2
    return Math.round(number * Math.pow(10, place)) / Math.pow(10, place);
}

// 除法
function div(num1,num2){
    var place1=place2=0
    try {
        place1= (num1+'').split('.')[1].length
    } catch (error) {}
    try {
        place2 += (num2+'').split('.')[1].length
    } catch (error) {}
    var place = Math.max(place1,place2)-Math.min(place1,place2)
    var number = num1 / num2
    return Math.round(number * Math.pow(10, place)) / Math.pow(10, place);
}

//数字的四舍五入
function round(number,place){
    return Math.round(number * Math.pow(10, place)) / Math.pow(10, place);
}