簡體   English   中英

Javascript | 浮點數字

[英]Javascript | floating point numbers

當使用小數點數字分配 2 個變量並計算它們的總和時使用 console.log() 返回結果,如果它們等於整數,則返回結果不帶小數點。

例如

 let num1 = 2.2;
 let num2 = 2.8;
console.log(num1 + num2 )

當我要求返回 5.0 時返回 5。

我試過 toFixed(1) 但測試需要返回各種數字

例如

let num1 = 2.22
 let num2 = 2.71
console.log((num1 + num2)toFixed(1))

當我需要 4.93 時返回 4.9

有沒有一種方法可以為變量分配一個浮點小數並保持其狀態,即使返回值是一個整數?

問題是你不知道加法前有多少位小數。

所以假設你想保留最長的小數位數,你可以這樣寫 function:

 function decimalPlaces(arr) { return Math.max(...arr.map(n => n.toString().split(".")[1].length)) } console.log((2.8 + 2.2).toFixed(decimalPlaces([2.8, 2.2]))) console.log((2.22 + 2.71).toFixed(decimalPlaces([2.22, 2.71]))) console.log((1.7 + 1.3001).toFixed(decimalPlaces([1.7, 1.3001])))

但是請注意,您必須將原始數字傳遞給數組中的 function ......由您決定它是否有用。

 function add(num1, num2) { const num1PointLength = String(num1).split(".")[1]?.length || 0; const num2PointLength = String(num2).split(".")[1]?.length || 0; return (num1 + num2).toFixed(num1PointLength > num2PointLength? num1PointLength: num2PointLength); } let num1 = 2.2; let num2 = 2.8; console.log(add(num1, num2));

toFixed()-> 該方法將字符串四舍五入到指定的小數位數。如果小數位數大於數字,則添加零。


let num1 = 2.2
let num2 = 2.8
console.log((num1 + num2).toFixed(1))

returns=> 5.0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM