JS retain decimal method

toFixed() method

n in toFixed(n) refers to the number of digits after the decimal point

1. Integers retain one decimal place

var num = 1
num = num.toFixed(1)   
console.log(num);   //1.0

2. One decimal place is reserved.
Note: Rounding up to five to get an even number - if the fifth is not zero, it will be rounded up;

var num = 1.55
var num1 = 1.45          //5前为偶舍去
num1 = num1.toFixed(1)
num = num.toFixed(1)   
console.log(num);   //1.6
console.log(num1);  //1.4

2. User-defined conversion method - rounded up, it is still a number type after conversion

  • The first parameter is the number to be converted, which is a decimal, and the integer cannot be implemented
  • The second parameter is the number of decimals to keep
function roundFun(value, n) {
    
    
  return Math.round(value*Math.pow(10,n))/Math.pow(10,n);
}
console.log(roundFun(2.8532));  //2.85
console.log(roundFun(5/3, 2)     //1.67
console.log(roundFun(2, 2)       //2      
//输入小数value,并保留小数点后一位,如果想保留两位,将10改为100
function roundFun(value) {
    
    
    return Math.round(value * 10) / 10;
}
console.log(roundFun(2.853));      //2.9

3. Custom formatted output method - a supplement to the above custom conversion method

  • The number of decimal places is rounded, and the formatted string is returned instead of a number. The insufficient digits after the decimal point will be automatically filled with 0, such as 4 will become 4.0 and returned
//保留n位小数并格式化输出(不足的部分补0)
    function fomatFloat(value, n) {
    
    
      var f = Math.round(value * Math.pow(10, n)) / Math.pow(10, n);
      var s = f.toString();
      var rs = s.indexOf(".");
      if (rs < 0) {
    
    
        s += ".";
      }
      for (var i = s.length - s.indexOf("."); i <= n; i++) {
    
    
        s += "0";
      }
      return s;
    };
    console.log(fomatFloat(1,2));    //1.00

Guess you like

Origin blog.csdn.net/qq_50630857/article/details/129460332