About float operations in JS

About float operations in JS
0

#1

I find it hard to control the accuracy of float in JS.
for example:

var num1 = 0.60;
var num2 = 0.40;

I want to get the result of (num1- num2)

I have tried many methods, but the result is 0.2 instead of 0.20.
what should I do to keep two decimal places?


#2

You can use toFixed to specify how many decimal places you want to show.

var num = 0.2;
var numFormatted = num.toFixed(2);

console.log(numFormatted); // "0.20"

Note that the return value of toFixed is a string, no longer a number.