Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse to float with 2 decimal places

Tags:

javascript

I need to round a value with 2 decimal places that I receive from a web service. To do this i use this methods toFixed and parseFloat because I need the final value in a float. However when I have this value "5.5000000" he shows me the value with only one decimal place "5.5"...

I did in that way:

var num = 5.5000000;
var n = num.toFixed(2);
var numFinal = parseFloat(n);
like image 752
sampaioPT Avatar asked Oct 29 '25 11:10

sampaioPT


2 Answers

You have to call toFixed after parseFloat:

parseFloat(yourString).toFixed(2)
like image 200
Andrei Zhytkevich Avatar answered Nov 01 '25 00:11

Andrei Zhytkevich


Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

  1. Either use data as a string or
  2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal
like image 28
abhinav pandey Avatar answered Nov 01 '25 00:11

abhinav pandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!