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
  • 21,138
  • 10
  • 54
  • 85
AMAR MAGAR
  • 107
  • 1
  • 12
  • 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
  • 8,693
  • 8
  • 27
  • 56
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
  • 21,138
  • 10
  • 54
  • 85
1

use parseFloat().toFixed() like this :

var number = parseFloat(4).toFixed(2);
console.log(number);
Rio A.P
  • 1,038
  • 11
  • 19
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
  • 6
  • 29