15

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?

user1749458
  • 153
  • 1
  • 1
  • 6

7 Answers7

29
int x = 100;
DecimalFormat df = new DecimalFormat("#.00"); // Set your desired format here.
System.out.println(df.format(x/100.0));
Juvanis
  • 25,802
  • 5
  • 69
  • 87
  • 1
    This is not a valid format for `100` it should print `1.00` as per OP expectations where as it prints `100.00`. There is no point in using this. – Amit Deshpande Oct 20 '12 at 16:58
  • @AmitD I guess the OP's question was not clear when I posted this answer. now I see what OP expects. I edited my answer with a very slight change. (x became x/100.0) – Juvanis Oct 20 '12 at 18:38
  • Hi @BlueBullet will you elaborate the meaning of `OP` as I don't understand for what it is stands for? :) – The iOSDev Nov 19 '12 at 05:30
  • @Wolvorin hi wolvorin bro =) I was novice about it in the past just like you. Now I know and use it. OP means "Original Poster" or let's say owner of the post. – Juvanis Nov 19 '12 at 06:20
12

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
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
5

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);
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
2

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));
Community
  • 1
  • 1
YoYo
  • 9,157
  • 8
  • 57
  • 74
1

You can try this:-

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

or

NumberFormat f = NumberFormat.getNumberInstance();
f.setMinimumFractionDigits(2);
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

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

0

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.