1

In java, I want to do 102%100 and get the remainder as 02 and not as 2.. How do i do that?

int a = (102%100);

a returns 2 and not 02.. I want to get 02.. because originally, it's supposed to be 1.02, but mod returns 2. :( Anybody know how to do that?

황현정
  • 3,451
  • 6
  • 28
  • 35

4 Answers4

5

2 and 02 are the same number.

Since you are using this to find the first two numbers after the decimal-point, just pad any one-digit numbers with a 0. If you want all the numbers after the decimal-point, the more usual way is to do this:

//Strip all numbers before decimal-point
double decimalDigits = myNumber - (int)myNumber;
BlueRaja - Danny Pflughoeft
  • 84,206
  • 33
  • 197
  • 283
  • is there no automatic way to do that? T_T – 황현정 Dec 12 '11 at 02:56
  • 1
    @황현정: If you are only doing this for ease of display, then yes, there is; in fact, you can automatically format decimals without all this hoopla. Check out the [string formatter](http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html) classes. – BlueRaja - Danny Pflughoeft Dec 12 '11 at 02:58
3

NumberFormat is probably the best way to go. String.format and doing calculations also work, but since you're formatting a number, might as well use a number formatter.

An example. I'm guessing on your requirements here a bit (e.g. what should 110%100 return, or do you only expect a single-digit remainder?):

NumberFormat formatter = new DecimalFormat("'0'#");
int remainder = 102%100;
System.out.println(formatter.format(remainder));
Chip McCormick
  • 744
  • 4
  • 17
1

As integers, they represent the same number. Use the following to format the number as a string for display purposes:

int a = 102 / 100;
int r = 102 % 100;
System.out.print(a + "." + String.format("%02d", r));

Output:

1.02
Wayne
  • 59,728
  • 15
  • 131
  • 126
0

Here lies the answer to padding numbers with zeroes: Add leading zeroes to number in Java?

Really though, thats it.

Community
  • 1
  • 1
Jon Egeland
  • 12,470
  • 8
  • 47
  • 62