Print Integer with 2 decimal places in Java

后端 未结 7 892
轻奢々
轻奢々 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);
    
    0 讨论(0)
  • 2020-12-16 15:40

    You can try this:-

    new DecimalFormat("0.00######");
    

    or

    NumberFormat f = NumberFormat.getNumberInstance();
    f.setMinimumFractionDigits(2);
    
    0 讨论(0)
  • 2020-12-16 15:43

    you can use double instate of int. it gives you a output with decimals.

    if you want the number to stand behind the dot. you can use this:

    **int number=100;
    double result;
    result=number/(number.length-1);**
    

    I hope you can you use this.

    0 讨论(0)
  • 2020-12-16 15:46

    I would say to use 0.00 as format:

          int myNumber = 10;
          DecimalFormat format = new DecimalFormat("0.00"); 
          System.out.println(format.format(myNumber));
    

    It will print like:           

          10.00
    

    The advantage here is:

    If you do like:

          double myNumber = .1;
          DecimalFormat format = new DecimalFormat("0.00"); 
          System.out.println(format.format(myNumber));
    

    It will print like:

          0.10
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-12-16 15:51

    you can use double instate of int. it gives you a output with decimals. and then you can divide with 100.

    0 讨论(0)
提交回复
热议问题