DIV CSS 佈局教程網

JavaScript 保留小數點後 N 位的完整實作指南
編輯:關於JavaScript     

在 JavaScript 中處理小數位數是很常見的需求,最直覺的做法就是使用 toFixed 方法。本文整理了多種保留小數的寫法,並深入說明背後的原理。

使用 toFixed 方法

toFixed 是最簡便的方式,直接指定要保留的小數位數即可。

程式碼如下:

<script language="javascript">
document.write("<h1>JS 保留兩位小數範例</h1><br>");
var a = 2.1512131231231321;
document.write("原來的值:" + a + "<br>");
document.write("兩位小數點:" + a.toFixed(2) + "<br>四位小數點" + a.toFixed(4));
</script>

自訂的四捨五入轉換函式

若想更靈活地控制放大與縮小的倍數,可以自己寫一個轉換函式:

function round(v, e) {
var t = 1;
for (; e > 0; t *= 10, e--);
for (; e < 0; t /= 10, e++);
return Math.round(v * t) / t;
}

參數說明:v 代表要轉換的數值,e 代表要保留的位數。函式中的兩個 for 迴圈是關鍵:第一個處理小數點右邊(保留幾位小數),第二個處理小數點左邊(保留幾位整數)。迴圈的作用是計算出 t 的值,也就是 v 需要放大或縮小的倍數。最後再呼叫原生的 round 方法計算放大後的結果,並縮回正確的倍數。

保留兩位小數的實際範例

以下整理了幾種常見的保留兩位小數寫法:

<script type="text/javascript">
// 保留兩位小數:將浮點數四捨五入至小數點後 2 位
function toDecimal(x) {
var f = parseFloat(x);
if (isNaN(f)) { return; }
f = Math.round(x * 100) / 100;
return f;
}
// 強制保留 2 位小數,例如 2 會補成 2.00
function toDecimal2(x) {
var f = parseFloat(x);
if (isNaN(f)) { return false; }
var f = Math.round(x * 100) / 100;
var s = f.toString();
var rs = s.indexOf('.');
if (rs < 0) { rs = s.length; s += '.'; }
while (s.length <= rs + 2) { s += '0'; }
return s;
}
function fomatFloat(src, pos) {
return Math.round(src * Math.pow(10, pos)) / Math.pow(10, pos);
}
// 四捨五入
alert("保留2位小數:" + toDecimal(3.14159267));
alert("強制保留2位小數:" + toDecimal2(3.14159267));
alert("保留2位小數:" + toDecimal(3.14559267));
alert("強制保留2位小數:" + toDecimal2(3.15159267));
alert("保留2位小數:" + fomatFloat(3.14559267, 2));
alert("保留1位小數:" + fomatFloat(3.15159267, 1));
// 五捨六入
alert("保留2位小數:" + 1000.003.toFixed(2));
alert("保留1位小數:" + 1000.08.toFixed(1));
alert("保留1位小數:" + 1000.04.toFixed(1));
alert("保留1位小數:" + 1000.05.toFixed(1));
// 科學計數
alert(3.1415.toExponential(2));
alert(3.1455.toExponential(2));
alert(3.1445.toExponential(2));
alert(3.1465.toExponential(2));
alert(3.1665.toExponential(1));
// 精確到 n 位
alert("精確到小數點第2位" + 3.1415.toPrecision(2));
alert("精確到小數點第3位" + 3.1465.toPrecision(3));
alert("精確到小數點第2位" + 3.1415.toPrecision(2));
alert("精確到小數點第2位" + 3.1455.toPrecision(2));
alert("精確到小數點第5位" + 3.141592679287.toPrecision(5));
</script>

以上就是 JavaScript 保留小數位數的常見做法,概念其實並不複雜,希望對大家有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved