0

I used parseFloat(number) but it output a int. for example:

var num='3.0';
console.log(parseFloat(num)) // 3, not 3.0

How do I convert string to number and ensure a float type with a decimal part?

jww
  • 97,681
  • 90
  • 411
  • 885
tulipjie
  • 33
  • 1
  • 4
  • 4
    `3.0` as a number is `3` - end of story - use `toFixed(1)` for chainging a number to a string - but then it's a string not a number – Jaromanda X Oct 09 '18 at 07:53
  • 1
    Also see [How to format a float in javascript?](https://stackoverflow.com/q/661562/608639) and [JavaScript equivalent to printf/String.Format](https://stackoverflow.com/q/610406/608639) – jww Oct 09 '18 at 08:04
  • but i don't want to make the decimal digits fixed to 1.could use some other methods ? – tulipjie Oct 09 '18 at 08:24
  • actually,in my code the number is getting from input.for example,user want to input 3.0.when user input 3.0,the number already turn to 3. – tulipjie Oct 09 '18 at 08:32
  • 2
    _“when user input 3.0,the number already turn to 3”_ - yes, and that _is_ the correct numeric representation of the _number_ three. You need to first of all learn to differentiate between the internal representation of a number, and its _formatted output_ for humans. `3.0` is the latter. Now if you say you want this “dynamic”, presumably meaning you want to keep as many decimals as the user entered, even if they are all zeros - then you need to determine that number of decimals _before_ you cast the thing into a number, using the original input while still in its string form. – misorude Oct 09 '18 at 09:32
  • @misorude: That would IMO be a valid answer. – Rudy Velthuis Oct 09 '18 at 09:36

3 Answers3

1

3.0 is 3 it's not wrong

if you do

var num='3.1';
console.log(parseFloat(num))//3.1

It will display 3.1 so nothing wrong with it

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
Dinosan0908
  • 1,082
  • 2
  • 8
  • 19
0

var num = '3.0';
console.log(Number.parseFloat(num).toFixed(1));
Sangsom
  • 437
  • 2
  • 6
  • 16
0

Rounding the value

var num='3.0'
console.log(Math.round(num));

Truncateing the value

var num = '3.0';
console.log(Math.floor(num));
console.log(Math.trunc(num))

check this link for more ways

sitaram9292
  • 171
  • 8