Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Round a number to 2 or more decimal places

I’m working in TypeScript. Is there an accepted way of rounding a number to n decimal places, or more, if the precision exists in the number?

The number must be represented as a string to avoid precision errors (e.g. 2.3 - 2 = 0.2999999999999998)

For example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

precision = [2, 6];

tx(0.000000, precision) => 0.00
tx(0.123123, precision) => 0.123123

tx(2.00, precision) => 2.00
tx(2, precision) => 2.00

tx(2.01, precision) => 2.01
tx(2.001, precision) => 2.001
tx(2.000000001, precision) => 2.00
tx(2.000001, precision) => 2.000001

I can use this to deal with funky epsilon errors while still allowing users to enter more precise numbers than a fixed DP.

>Solution :

Use toLocaleString with minimumFractionDigits and maximumFractionDigits parameters

function tx(value, [minimumFractionDigits, maximumFractionDigits]) {
  const result = value.toLocaleString('en-US', {
    minimumFractionDigits,
    maximumFractionDigits
  });
  
  console.log( {value, result} );
  return result;

}


const precision = [2, 6];

tx(0.000000, precision)
tx(0.123123, precision)

tx(2.00, precision)
tx(2, precision)

tx(2.01, precision)
tx(2.001, precision)
tx(2.000000001, precision)
tx(2.000001, precision)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading