Formatting a double and not rounding off

前端 未结 5 1714
旧时难觅i
旧时难觅i 2020-12-18 21:23

I need to format (and not round off) a double to 2 decimal places.

I tried with:

String s1 = \"10.126\";
Double f1 = Double.pa         


        
5条回答
  •  悲&欢浪女
    2020-12-18 22:14

    If all you want to do is truncate a string at two decimal places, consider using just String functions as shown below:

    String s1 = "10.1234";
    String formatted = s1;
    int numDecimalPlaces = 2;
    int i = s1.indexOf('.');
    if (i != -1 && s1.length() > i + numDecimalPlaces) {
        formatted = s1.substring(0, i + numDecimalPlaces + 1);
    }
    System.out.println("f1" + formatted);
    

    This saves on parsing into a Double and then formatting back into a String.

提交回复
热议问题