Wednesday, July 24, 2013

Floating-Point Literals

Floating-point literals are of type double by default, so 1.0 and 345.678 are both of type double. When you want to specify a value of type float, you just append an f, or an F, to the value, so 1.0f and 345.678F are both literals of type float. If you are new to programming it is important to note that you must not include commas as separators when specifying numerical values in your program code. Where you might normally write a value as 99,786.5, in your code you must write it without the comma, as 99786.5.

When you need to write very large or very small floating-point values, you will usually want to write them with an exponent - that is, as a decimal value multiplied by a power of 10. You can do this in Java by writing the number as a decimal value followed by an E, or an e, preceding the power of 10 that you require. For example, the distance from the Earth to the Sun is approximately 149,600,000 kilometers, more conveniently written as 1.496E8. Since the E (or e) indicates that what follows is the exponent, this is equivalent to 1.496 * 108. At the opposite end of the scale, the mass of an electron is around 0.0000000000000000000000000009 grams. This is much more convenient, not to say more readable, when it is written as 9.0E-28 grams.

No comments:

Post a Comment

Thanks for Commenting......