Computer >> Computer tutorials >  >> Programming >> Javascript

JavaScript subtraction of two float values?


To correctly subtract two float values, use parseFloat() along with toFixed().

Example

Following is the code −

var firstValue=4.3;
var secondValue=3.8;
console.log("The first Value="+parseFloat(firstValue).toFixed(1)+" The
second Value="+parseFloat(secondValue).toFixed(1))
var result = parseFloat(firstValue).toFixed(1) -
parseFloat(secondValue).toFixed(1);
console.log("Result is="+result);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo309.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo309.js
The first Value=4.3 The second Value=3.8
Result is=0.5