How can I make a whole number be a decimal number with two decimal places in javascript?

236 views Asked by At

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"
2

There are 2 answers

0
jfriend00 On

You can use val.toFixed(2) to get two decimal points:

let x = 18;
let y = 18.1;
let z = 18.11;

console.log(x.toFixed(2));    // 18.00
console.log(y.toFixed(2));    // 18.10
console.log(z.toFixed(2));    // 18.11

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.

4
Jenson M John On

JavaScript toFixed() method formats a number using fixed-point notation.

Example.

let a = [18, 18.1, 18.11, 18.111, 18.445];
for(v of a){
    console.log(v.toFixed(2));
}

The above Code Prints..

18.00
18.10
18.11
18.11
18.45

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.