在Java中格式化浮点值

时间:2014-03-13 01:14:17

标签: java

我试着用这个:

String t="4.99999999";
t = String.format("%.2f",Float.valueOf(t));

我想要它打印4.99,但它写了5.00。你知道为什么吗?

4 个答案:

答案 0 :(得分:3)

这里有两个问题。一个是浮点数不能区分4.999999995.0,即Float.valueOf()将其解析为5.0。双打有足够的精确度。另一个问题是5.0是%2f的正确行为。你要求两个小数点,而4.99999999明确地向上舍入到5.00。由于String.format()行为不是你想要的,你想要什么,即为什么是4.99正确的用例行为?

编辑:如果您尝试截断两个小数点,请查看此处:How can I truncate a double to only two decimal places in Java

答案 1 :(得分:1)

如果您希望它显示4.99为什么不提取子字符串

String t="4.99999999";
int i =  t.indexOf('.');
if(i != -1){
    t = t.substring(0, Math.min(i + 3, t.length()));
}

如果您希望它总是有两个小数位,那么您使用BigDecimal。使用BigDecimal,您可以将比例设置为2位小数并向下舍入,因此4之类的数字会打印出4.00

 String t="4";
 BigDecimal bd = new BigDecimal(t).setScale(2, BigDecimal.ROUND_DOWN);
 System.out.println(bd); //prints out 4.00

答案 2 :(得分:1)

一般来说,在考虑十进制数时,一定不能使用浮点数(或双精度数)。

简单示例:

System.out.println(0.33333333333333333 + 0.1);

将打印:

0.43333333333333335

Java将在内部存储浮点数并加倍为"二进制值"。将十进制派系转换成二进制分数会引起许多令人惊讶的事情。

如果你想处理小数,你必须使用BigDecimal或类似的类。

如何使用它的一个例子:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Snippet {

    public static void main(String[] args) {

        // define the value as a decimal number
        BigDecimal value = new BigDecimal("4.99999999");

        // round the decimal number to 2 digits after the decimal separator
        // using the rounding mode, that just chops off any other decimal places
        value.setScale(2, RoundingMode.DOWN);

        // define a format, that numbers should be displayed like
        DecimalFormat format = new DecimalFormat("#.00");

        // use the format to transform the value into a string
        String stringRepresentation = format.format(value);

        // print string
        System.out.println(stringRepresentation);
    }
}

答案 3 :(得分:0)

尝试

System.out.println(((int)(Float.valueOf(t) * 100))/100.0);