user1722101
user1722101

Reputation: 31

getting the remainder using Java

I can get the remainder when dividing a number, but if I were to divide 306 by 100. e.g. 306 / 100 = 3

but if I goto find the remained by the % operator, I want to get 06 back, for example

desired

306 % 100 = 06

what actually happens

306 % 100 = 6

is there a way to get around this so that two digits are return instead of the one?

Upvotes: 3

Views: 433

Answers (5)

Cory Kendall
Cory Kendall

Reputation: 7324

Split it into two parts; first get the mathematically correct answer 6, and then present it any way you want. If you want always two digits, you could use:

int x = 306 % 100;
System.out.format("%02d", x);

Upvotes: 1

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33544

I this 6 and 06 is just the same value, but still if you want to get the value as 6, then try this..

NumberFormat df = new DecimalFormat("00");
System.out.println(df.format(6));

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213371

Actually for any computer language, a single digit integer number doesn't need a leading zero. You will never get this as output in any language..

However, if you want it to get printed like this, you can format your value accordingly: -

System.out.format("%02d", 6);
  • First 0 denote that you want to pad your number with ZEROs, and the 2nd value (2) denotes how many 0's you want..

Upvotes: 1

ajuch
ajuch

Reputation: 415

This is just a matter of formatting the number. See here.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503290

You're getting a number back. 6 and 06 are the same value. An int (and similar types) don't have any concept of leading digits.

If you want to format the number in a particular way, when you convert it to a string (which is the only place this would matter) then that's simply a matter of choosing the right formatting code. Do you always want two digits? Use a format of "00" with DecimalFormat.

import java.text.*;

class Test {

    public static void main(String args[]) throws Exception {
        NumberFormat format = new DecimalFormat("00");
        int value = 6;
        System.out.println(format.format(value)); // 06
    }
}

(Or use String.format, or some other way of formatting. The important point is that the number 6 is just a number; separate the number from its textual representation in your mind.)

Upvotes: 13

Related Questions