-1

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"
juju11
  • 17
  • 4
  • What did you try and what went wrong? You might find these helpful: [JavaScript displaying a float to 2 decimal places](https://stackoverflow.com/questions/3163070/javascript-displaying-a-float-to-2-decimal-places) and [Format number to always show 2 decimal places](https://stackoverflow.com/questions/6134039/format-number-to-always-show-2-decimal-places) – showdev May 19 '23 at 04:22

2 Answers2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

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.

Jenson M John
  • 5,499
  • 5
  • 30
  • 46
  • FYI, you should never use `for/in` with arrays as it enumerates all enumerable properties on the object, not necessarily just the array elements. Use `for/of` instead which will use the object's iterator which (for an array) iterates only the array elements, even if the object has other properties. – jfriend00 May 19 '23 at 04:47
  • Ok. Thanks for the input. I hope there is no problem to use it for an Example – Jenson M John May 19 '23 at 05:15
  • Why don't you edit your example to show it the way it should be coded? It would take 5 seconds of editing to show the proper way. – jfriend00 May 19 '23 at 05:35
  • @jfriend00 Changed. Thanks for Your Inputs. – Jenson M John May 19 '23 at 16:39