Skip to content

Instantly share code, notes, and snippets.

@mikechambers
Created January 6, 2022 20:34
Show Gist options
  • Save mikechambers/6f5a70cc878bff19d9dcdfb184787eb3 to your computer and use it in GitHub Desktop.
Save mikechambers/6f5a70cc878bff19d9dcdfb184787eb3 to your computer and use it in GitHub Desktop.
Examples of how to format floating point numbers in JavaScript
let output = 123.456789;
let precision = 2;
let mod = Math.pow(10, precision);
let a = Math.round(output * mod) / mod;
let b = output.toFixed(2);
console.log(a);
console.log(b);
/*
main differences is that toFixed, will always return the precision value,
padding with zeros if necessary, where as Math.round will not pad.
Also, Math.round returns a number, while toFixed returns a string.
*/
output = 123;
a = Math.round(output * mod) / mod;
b = output.toFixed(2);
console.log(a, typeof a); //number
console.log(b, typeof b); //string
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment