Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Trừ hai số thực (float) chính xác trong JavaScript


Để trừ chính xác hai số float, dùng parseFloat() kết hợp toFixed().

Ví dụ

Mã thực hiện:

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);

Chạy lệnh:

node fileName.js.

Tên file: demo309.js.

Kết quả

Đầu ra:

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