You can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
Answer from Mahesh Velaga on Stack OverflowYou can use toFixed() to do that
var twoPlacedFloat = parseFloat(yourString).toFixed(2)
If you need performance (like in games):
Math.round(number * 100) / 100
It's about 100 times as fast as parseFloat(number.toFixed(2))
http://jsperf.com/parsefloat-tofixed-vs-math-round
EDIT:
https://jsperf.app/kowulu
parsing string to decimal doesn't return decimals JavaScript - Stack Overflow
alternative to JSON.parse() for maintaining decimal precision?
convert a JavaScript string variable to decimal/money - Stack Overflow
math - parseDecimal in JavaScript? - Stack Overflow
» npm install parse-decimal-number
In Javascript everything is Number, which is double-precision floating point 64 bit number (=decimal).
100.00 is equal to 100, therefore it shows you 100.
What you are asking is not possible, the decimal 100 is not representable as 100.00 as number, you can only represent it as a String with help of toFixed;
var num = 100;
var strNum = num.toFixed(2); // in this case you have a string instead of a number
console.log(typeof num, num);
console.log(typeof strNum, strNum);
Run code snippetEdit code snippet Hide Results Copy to answer Expand
I'm calling JSON.parse() to parse a JSON string which has small decimals. The precision of the decimals is not being maintained. For example, a value like 3.1e-7 is being returned instead of the actual decimal. Do you have any recs for how I can deserialize a json string in ng2+ while maintaining the decimal precision?
Yes -- parseFloat.
parseFloat(document.getElementById(amtid4).innerHTML);
For formatting numbers, use toFixed:
var num = parseFloat(document.getElementById(amtid4).innerHTML).toFixed(2);
num is now a string with the number formatted with two decimal places.
You can also use the Number constructor/function (no need for a radix and usable for both integers and floats):
Number('09'); /=> 9
Number('09.0987'); /=> 9.0987
Alternatively like Andy E said in the comments you can use + for conversion
+'09'; /=> 9
+'09.0987'; /=> 9.0987