js implements a rounding method that completely preserves two decimal places

  • 2021-07-07 06:31:52
  • OfStack

In this paper, an example is given to describe the method of js to realize 4 rounding and 5 entering and completely retain two decimal places. Share it for your reference, as follows:


//4 Shed 5 Entry reservation 2 Decimal places (if the first 2 The decimal number of bits is 0 Is retained 1 Decimal bits) 
function keepTwoDecimal(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    alert(' Error in passing parameters, please check! ');
    return false;
  }
  result = Math.round(num * 100) / 100;
  return result;
}
//4 Shed 5 Entry reservation 2 Decimal digits (if there are not enough digits, use 0 Substitutes) 
function keepTwoDecimalFull(num) {
  var result = parseFloat(num);
  if (isNaN(result)) {
    alert(' Error in passing parameters, please check! ');
    return false;
  }
  result = Math.round(num * 100) / 100;
  var s_x = result.toString();
  var pos_decimal = s_x.indexOf('.');
  if (pos_decimal < 0) {
    pos_decimal = s_x.length;
    s_x += '.';
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0';
  }
  return s_x;
}

More readers interested in JavaScript can check the topics of this site: "Summary of JavaScript Mathematical Operation Usage", "Summary of json Operation Skills in JavaScript", "Summary of JavaScript Switching Special Effects and Skills", "Summary of JavaScript Search Algorithm Skills", "Summary of JavaScript Animation Special Effects and Skills", "Summary of JavaScript Error and Debugging Skills", "Summary of JavaScript Data Structure and Algorithm Skills" and "Summary of JavaScript Traversal Algorithm and Skills"

I hope this article is helpful to everyone's JavaScript programming.


Related articles: