Number to Float Conversion in JavaScript

Viewed 155

I want Conversion from Number to Float in JavaScript

function circumference(r) {
  return parseFloat(r);
}
console.log(circumference(4));

expected output: 4.00

4 Answers

Use Number.prototyp.toFixed() function. You can pass the number of decimal places as the argument.

function circumference(r) {
  return r.toFixed(2);
}
console.log(circumference(4));

use parseFloat().toFixed() like this :

var number = parseFloat(4).toFixed(2);
console.log(number);

There's a detailed explanation given on w3Schools with this link having the example to it.

var num = 5.56789;
var n = num.toFixed(2);
console.log(n);

Hope this helps.

Related