I have a variable with a type of number. If the number is 0 or a whole number, it should return as a string with two decimal numbers like "##.00". For example:
- 18: number -> "18.00"
- 18.1: number -> "18.10"
- 18.11: number -> "18.11"
I have a variable with a type of number. If the number is 0 or a whole number, it should return as a string with two decimal numbers like "##.00". For example:
2
Answers
You can use
val.toFixed(2)
to get two decimal points:Relevant doc for
.toFixed()
.Note:
.toFixed()
creates a string with the requested number of digits after the decimal point in the string since the numeric value itself doesn’t have formatting. So, pretty much by definition, creating any format will create a string from your number that displays in that format.The default
.toString()
string conversion shows just the significant digits before and after the decimal point with no extra trailing zeroes at the end.JavaScript
toFixed()
method formats a number using fixed-point notation.Example.
The above Code Prints..
Please note, The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.