Java:将float转换为字符串并在点

时间:2017-03-21 18:10:56

标签: java casting floating-point precision bigdecimal

当我想要像#34; 1234.5678930E8F" 1234.5678930E8F"对于Long / BigDecimal / String格式/类型,我没有得到" 123456789300"例如:

    Float test = 1234.5678930E8F;
    BigDecimal testB = new BigDecimal( test, MathContext.DECIMAL64 );
    System.out.println( testB );
    System.out.println( test );
    System.out.println( test.longValue() );

我出来了:

 123456790528
 1.23456791E11
 123456790528

但我需要精确的价值。

1 个答案:

答案 0 :(得分:0)

经过大量测试后,使用Double代替Float以获得更好的精度。正如约翰·博林格所说的那样。

    Double testing = 1234.5678930E8;
    BigDecimal testB = new BigDecimal( testing, MathContext.DECIMAL64 ).setScale(2, RoundingMode.CEILING);;
    System.out.println( testB);

输出:

123456789300.00

在此Link

中查看有关舍入的详情