Bijilesh
Bijilesh

Reputation: 23

Unexpected number formatting in printed String

By mistake i have entered the below line in my JAVA code and got a surprising output. Can anyone please help me to understand how it is happening.

Code: System.out.printf("Value :"+0.40+010+0.60);

Output: value :0.480.6

Upvotes: 2

Views: 74

Answers (2)

duffymo
duffymo

Reputation: 308938

You're imagining that addition is being done, but it's not. These are strings.

First value is 0.4.

Second value is 010, which means octal. That translates to 8 in decimal.

Third value is 0.6

You don't say what you expected to see. If you really wanted addition to happen, I'd recommend enclosing in parentheses to make the addition happen. You'll still have to decide if that octal value was intentional or a typo.

Upvotes: 2

Thirler
Thirler

Reputation: 20760

You are seeing several things:

  1. You are adding the numbers as strings to the value string.
  2. You are writing an octal number (010), because you start the literal number with a 0, which really means 8 in decimals.
  3. Trailing decimal zeroes are removed from literals. (0.40 -> 0.4)

So rewriting your code in several steps gives:

  1. "Value :"+0.40+010+0.60
  2. "Value :0.4"+010+0.60
  3. "Value :0.4"+8+0.60
  4. "Value :0.48"+0.60
  5. "Value :0.480.6"

Upvotes: 3

Related Questions