更新时间:2022-10-15 19:52:38
从Java语言规范,在浮点文字
FloatingPointLiteral:
>
- DecimalFloatingPointLiteral
$- 数字。 [Digits] [ExponentPart] [FloatTypeSuffix]
- 。 Digits [ExponentPart] [FloatTypeSuffix]
- 数字ExponentPart [FloatTypeSuffix]
- 数字[ExponentPart] FloatTypeSuffix
其中数字
位数:
- 数字
- 数字 [DigitsAndUnderscores] Digit
DigitAndUnderscores:
- DigitOrUnderscore {DigitOrUnderscore}
DigitOrUnderscore:
- 数字
- _
下划线: / ul>
对于浮点文字,您可以有任意数量的前导 0
。
我无法在JLS中找到任何解释为何允许这样做的内容,但是我可以想象它简化了解析。
Using "0" (zero) as a prefix in an integer literal changes its base to octal. This is why
System.out.println(010);
will print 8
. But using "F" as a suffix
System.out.println(010F);
will make it float losing octal base (going back to decimal) and will print 10.0
.
Is there any difference between 010F
and 10F
? Has the "0" prefix any kind of meaning when working with floats?
From the Java Language Specification, on Floating Point literals
FloatingPointLiteral:
- DecimalFloatingPointLiteral
- HexadecimalFloatingPointLiteral
DecimalFloatingPointLiteral:
- Digits . [Digits] [ExponentPart] [FloatTypeSuffix]
- . Digits [ExponentPart] [FloatTypeSuffix]
- Digits ExponentPart [FloatTypeSuffix]
- Digits [ExponentPart] FloatTypeSuffix
where Digits
Digits:
- Digit
- Digit [DigitsAndUnderscores] Digit
Digit:
- 0
- NonZeroDigit
DigitsAndUnderscores:
- DigitOrUnderscore {DigitOrUnderscore}
DigitOrUnderscore:
- Digit
- _
Underscores:
- _ {_}
You can have any number of leading 0
for floating point literals.
I cannot find anything in the JLS that explains why this is allowed, but I can imagine it simplifies parsing.