在进行金额计算,及某些精确计算时,会出现意想不到的很多小数的情况。
- 对Java
采用BigDecimal,如下代码示例
package number; import java.math.BigDecimal; public class NumberTest { public static void main(String[] args){ double a = 2.05d; BigDecimal c = new BigDecimal(a); System.out.println("using double--"); System.out.println("a * 100 = " + a + " * 100 = " + a*100); System.out.println("using BigDecimal--"); BigDecimal m = new BigDecimal("2.05").multiply(new BigDecimal(100)); //<-- please use this. System.out.println("a * 100 = " + a + " * 100 = " + m); BigDecimal n = new BigDecimal(2.05d).multiply(new BigDecimal(100)); System.out.println("a * 100 = " + a + " * 100 = " + n); } }
上面程序输出的结果为:
using double-- a * 100 = 2.05 * 100 = 204.99999999999997 using BigDecimal-- a * 100 = 2.05 * 100 = 205.00 a * 100 = 2.05 * 100 = 204.99999999999998223643160599749535322189331054687500
- Javascript
使用parseFloat函数和toPrecision(12)函数。
var c=3.4-3; alert(c); alert(parseFloat(c).toPrecision(12)));