Print Integer with 2 decimal places in Java

2020-02-10 03:29发布

问题:

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?

回答1:

int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));


回答2:

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


回答3:

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);


回答4:

You can try this:-

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

or

NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);


回答5:

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));


回答6:

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



回答7:

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.