JAVA double 保留小数点后两位

public class NumberUtils {

    private NumberUtils() {
    }

    public static String doubleToString(Double value) {
        BigDecimal b = BigDecimal.valueOf(value).setScale(2, BigDecimal.ROUND_HALF_UP);
        return b.toString();
    }
}

Test:

@RunWith(JUnit4.class)
public class NumberUtilsTest {

    @Test
    public void testDoubleToString() {
        Double d = new Double(0.33333333333333);
        System.out.println(d);
        System.out.println(NumberUtils.doubleToString(d));
        Double test = 0.43;
        System.out.println(Double.toString(test - 0.13));
        System.out.println(NumberUtils.doubleToString(test - 0.13));
        assertTrue(NumberUtils.doubleToString(0.455).equals("0.46"));
        assertTrue(NumberUtils.doubleToString(0.454).equals("0.45"));
    }
}

猜你喜欢

转载自blog.csdn.net/wuzhong8809/article/details/106260163
今日推荐