Example of the rounding problem for JS implementation preserving n decimal places

  • 2021-07-07 06:30:22
  • OfStack

In this paper, an example is given to describe the problem of 4 rounding and 5 entering in JS to preserve the decimal places of n. Share it for your reference, as follows:


// Figures 4 Shed 5 Enter (retained n Decimal bits) 
getFloat = function (number, n) { 
  n = n ? parseInt(n) : 0; 
  if (n <= 0) return Math.round(number); 
  number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n); 
  return number; 
};
/*
// Usage example: 
alert(getFloat(2.085,2));
// Get 2.09
*/

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: