简体   繁体   中英

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

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"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM