Created
January 6, 2022 20:34
-
-
Save mikechambers/6f5a70cc878bff19d9dcdfb184787eb3 to your computer and use it in GitHub Desktop.
Examples of how to format floating point numbers in JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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