2

I want Conversion from Number to Float in JavaScript

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

expected output: 4.00

Charlie
  • 22,886
  • 11
  • 59
  • 90
AMAR MAGAR
  • 137
  • 2
  • 13
  • 1
    Your code doesn't make sense. The function `parseFloat` expects a string, but you give it a number. Can you add a little bit of context so that we can understand what you _really_ want to achieve? – Roland Illig Oct 10 '19 at 05:09
  • Possible duplicate of [How to format a float in javascript?](https://stackoverflow.com/questions/661562/how-to-format-a-float-in-javascript) – Charlie Oct 10 '19 at 06:04

4 Answers4

2

You can use toFixed()

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

function financial(x) {
  return Number.parseFloat(x).toFixed(2);
}

console.log(financial(4));
kyun
  • 9,710
  • 9
  • 31
  • 66
2

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));
Charlie
  • 22,886
  • 11
  • 59
  • 90
1

use parseFloat().toFixed() like this :

var number = parseFloat(4).toFixed(2);
console.log(number);
Rio A.P
  • 1,313
  • 13
  • 20
0

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.

Jennis Vaishnav
  • 331
  • 7
  • 29