有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java浮点值格式

我试着用这个:

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

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


共 (4) 个答案

  1. # 1 楼答案

    试一试

    System.out.println(((int)(Float.valueOf(t) * 100))/100.0);
    
  2. # 2 楼答案

    这里有两个问题。一个是float不能区分4.999999995.0,即Float.valueOf()将其解析为5.0。doubledo具有足够的精度。另一个问题是5.0是%2f的正确行为。您要求的是两个小数点,4.9999999显然四舍五入为5.00。既然String.format()行为不是您想要的,那么您想要什么,即为什么4.99是您用例的正确行为

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

  3. # 3 楼答案

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

    简单的例子:

    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);
        }
    }
    
  4. # 4 楼答案

    如果希望它显示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