天天看點

一種JavaScript裡小數的精确計算方式

<html>
<script type="text/javascript">
/*
    題目描述
求 a 和 b 相乘的值,a 和 b 可能是小數,需要注意結果的精度問題 
輸入例子:
multiply(3, 0.0001)
輸出例子:
0.0003

String.prototype.substring()(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/substring)

Number.prototype.toFixed()(https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed)

// 推薦寫法
*/
function multiply(a, b) {
    a = a.toString();
    b = b.toString();
    var aLen = a.substring(a.indexOf('.') + 1).length;
    var bLen = b.substring(b.indexOf('.') + 1).length; 
    
    return (a * b).toFixed(Math.max(aLen, bLen));
    /* 本題未說明保留小數位數, 這裡假定得出的結果不含多餘的0, 即0.0003000...需轉成0.0003 */
}

console.log( "Solution:" + multiply( 3, 0.0001 ));
console.log( 3 * 0.0001 );

console.log( "Solution: " + multiply( 3.0001, 0.0002 ));
console.log( 3.0001 * 0.0002 );
</script>
</html>      

繼續閱讀