package com.pksniq; import java.math.*; public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BigDecimal big = new BigDecimal("0"); float f = 0; double d = 0; for(int j = 0; j<10; j++){ f += 0.1; } System.out.println(f); //1.0000001 for(int j = 0; j<10; j++){ d += 0.1; } System.out.println(d); //0.9999999999999999 for(int j = 0; j<10; j++){ big = big.add(new BigDecimal("0.1")); } System.out.println(big.doubleValue()); //1.0 } }
Java 的浮点数运算问题
本文通过对比float、double与BigDecimal三种类型在累加操作中的表现,揭示了浮点数运算中常见的精度损失问题,并展示了如何使用BigDecimal来避免这类问题。

被折叠的 条评论
为什么被折叠?



