skip to Main Content

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

Answers


  1. 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.

    Login or Signup to reply.
  2. JavaScript toFixed() method formats a number using fixed-point notation.

    Example.

    let a = [18, 18.1, 18.11, 18.111, 18.445];
    for(i in a){
        console.log(a[i].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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search