Print Integer with 2 decimal places in Java

后端 未结 7 930
轻奢々
轻奢々 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:38

    You can printout a decimal encoded as an integer by divising by their factor (as a double)

    int i = 10; // represents 0.10
    System.out.println(i / 100.0);
    

    prints

    0.1
    

    If you need to always show two decimal places you can use

    System.out.printf("%.2f", i / 100.0);
    

提交回复
热议问题