JavaScript Number Format - Decimal Precision

Introduction

JavaScript has built-in methods to format a number to a certain precision. They are toFixed and toPrecision, and are part of the Number object. Any browser that supports ECMAScript version 3 should support toFixed and toPrecision. This roughly equates to Netscape 6.0 and above and IE 5.5 and above.

Examples

Use toFixed to set precision after the decimal point. It doesn't matter how large the number is before the decimal point. For normal decimal formatting, this is your best option.

// Example: toFixed(2) when the number has no decimal places
// It will add trailing zeros
var num = 10;
var result = num.toFixed(2); // result will equal 10.00
// Example: toFixed(3) when the number has decimal places
// It will round to the thousandths place
num = 930.9805;
result = num.toFixed(3); // result will equal 930.981

Try toFixed

 

 Input  
 Output  
   Places

 

Use toPrecision when you're setting the overall precision. Here, it matters how large the number is before and after the decimal point. This is more useful for mathematical purposes than for formatting.

// Example: toPrecision(4) when the number has 7 digits (3 before, 4 after)
// It will round to the tenths place
num = 500.2349;
result = num.toPrecision(4); // result will equal 500.2
// Example: toPrecision(4) when the number has 8 digits (4 before, 4 after)
// It will round to the ones place
num = 5000.2349;
result = num.toPrecision(4); // result will equal 5000
// Example: toPrecision(2) when the number has 5 digits (3 before, 2 after)
// It will round to the tens place expressed as an exponential
num = 555.55;
result = num.toPrecision(2); // result will equal 5.6e+2

Floating-point errors

toFixed and toPrecision are subject to floating-point errors.

Here is a test where the starting number is 162.295. The following should show the JavaScript results:

162.29 // toFixed(2)
162.29 // toPrecision(5)

Do they show up correctly as 162.30 in your browser? Most JavaScript implementations will display it as 162.29

Here is basically what happens when rounding 162.295 to two decimal places

num = 162.295
num *= 100 // 16229.499999999998
num = Math.round(num) // 16229
num /= 100 // 162.29

As you can tell, it's in the second step that the number changes from its actual value.

Floating-point numbers - External references

bugnet.com - JavaScript Math Errors in Netscape & Internet Explorer 
wikipedia.org - Problems with floating-point

转载于:https://www.cnblogs.com/yanbinboy/archive/2008/05/22/1204853.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值