Formatting a number with exactly two decimals in JavaScript

后端 未结 30 3213
广开言路
广开言路 2020-11-21 06:29

I have this line of code which rounds my numbers to two decimal places. But I get numbers like this: 10.8, 2.4, etc. These are not my idea of two decimal places so how I can

30条回答
  •  南旧
    南旧 (楼主)
    2020-11-21 06:43

    I didn't find an accurate solution for this problem, so I created my own:

    function inprecise_round(value, decPlaces) {
      return Math.round(value*Math.pow(10,decPlaces))/Math.pow(10,decPlaces);
    }
    
    function precise_round(value, decPlaces){
        var val = value * Math.pow(10, decPlaces);
        var fraction = (Math.round((val-parseInt(val))*10)/10);
    
        //this line is for consistency with .NET Decimal.Round behavior
        // -342.055 => -342.06
        if(fraction == -0.5) fraction = -0.6;
    
        val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
        return val;
    }
    

    Examples:

    function inprecise_round(value, decPlaces) {
      return Math.round(value * Math.pow(10, decPlaces)) / Math.pow(10, decPlaces);
    }
    
    function precise_round(value, decPlaces) {
      var val = value * Math.pow(10, decPlaces);
      var fraction = (Math.round((val - parseInt(val)) * 10) / 10);
    
      //this line is for consistency with .NET Decimal.Round behavior
      // -342.055 => -342.06
      if (fraction == -0.5) fraction = -0.6;
    
      val = Math.round(parseInt(val) + fraction) / Math.pow(10, decPlaces);
      return val;
    }
    
    // This may produce different results depending on the browser environment
    console.log("342.055.toFixed(2)         :", 342.055.toFixed(2)); // 342.06 on Chrome & IE10
    
    console.log("inprecise_round(342.055, 2):", inprecise_round(342.055, 2)); // 342.05
    console.log("precise_round(342.055, 2)  :", precise_round(342.055, 2));   // 342.06
    console.log("precise_round(-342.055, 2) :", precise_round(-342.055, 2));  // -342.06
    
    console.log("inprecise_round(0.565, 2)  :", inprecise_round(0.565, 2));   // 0.56
    console.log("precise_round(0.565, 2)    :", precise_round(0.565, 2));     // 0.57

提交回复
热议问题