Return decimal number as a Number type javascript

Viewed 45

I have a function which adds zeros to a number: for example, we input 10, the output would be 10.00.

The issue is that the result of the function is a string rather than a number type, is there a way to return 10.00 as a number in javascript?

const formatNumber = number => 
  number.toFixed(Math.max(((`${number}`).split('.')[1] || '').length, 2));
2 Answers

Number.prototype.toFixed() takes only either zero or one arguments. It should return a number after you use it. If it doesn't, for whatever reason, you can use String.prototype.toNumber() to turn it into a Number type.

I can't write comments due to lack of reputation, but I am trying to make my answer as detailed as possible so i can keep this answer.

You can use toFixed() function here instead of using split() and valueOf() to return a string as a number

<!DOCTYPE html>
<html>
<body>

<p>The toFixed() method returns a string with decimals:</p>

<p id="demo1"></p>

<p>The valueOf() method returns a number as a number:</p>

<p id="demo2"></p>

<script>
let x = 10;

x=x.toFixed(2); //toFixed(2) will return 10 with 2 decimal i.e. 10.00 as a string

document.getElementById("demo1").innerHTML = x;

document.getElementById("demo2").innerHTML = x.valueOf(); // valueOf() will return number here instead of string
</script>

</body>
</html>

Related