Print Integer with 2 decimal places in Java

后端 未结 7 917
轻奢々
轻奢々 2020-12-16 15:10

in my code i use integers multiplied by 100 as decimals (0.1 is 10 etc). Can you help me to format output to show it as decimal?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-16 15:51

    Based on another answer, using BigDecimal, this also works:

    BigDecimal v = BigDecimal.valueOf(10,2);
    System.out.println(v.toString());
    System.out.println(v.toPlainString());
    System.out.println(String.format("%.2f", v));
    System.out.printf("%.2f\n",v);
    

    Or even your good old DecimalFormat will work with BigDecimal:

    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println(df.format(v));
    

提交回复
热议问题