Why does +e canceled and -e not?
Asked Answered
H

2

5
System.out.println(2e+5);

Above line's output is,

200000.0

While below line's,

System.out.println(2e-5);

output is,

2.0e-5

Why does 2e-5 is not solved down with -10^5 giving the output,

0.00002
Herd answered 20/7, 2018 at 16:58 Comment(7)
One reason may be, that in the first case the extra digits may hold significant information, while in the second case they are always zero.Dowson
Because you're relying on the default formatting rules. 2e-5 is a double literal - it's 64 ones and zeroes. There is no format, no notation, no decimal point. How its represented when printed is just that, a representation. It's meaningless.Vagus
@Dowson the extra digits in 2eanything will always be zero...Vagus
@BoristheSpider in this case yes, but take 1.23456e5 and 1.23456e-5 for example.Dowson
In both cases you have shown numbers represented to 6 s.f. @Henry. All the digits are significant - that's what the "s" stands for! I'm really not sure what you mean.Vagus
@BoristheSpider you would get 123456.0 and 1.23456e-5 with the rules as they are. 0.0000123456 on the other hand uses a lot of 0 digits just to indicate the magnitude.Dowson
@Dowson ah, gotcha. That makes some sort of sense - but then 1.23456e10 has the same problems.Vagus
D
8

Because that's how the designers of the Double class chose to implement it:

[...]

  • If m is greater than or equal to 10-3 but less than 107, then it is represented as the integer part of m, in decimal form with no leading zeroes, followed by '.' ('\u002E'), followed by one or more decimal digits representing the fractional part of m.
  • If m is less than 10-3 or greater than or equal to 107, then it is represented in so-called "computerized scientific notation." [...]

They could have made another choice, of course, but that's simply how it is.

As the documentation says, if you want a specific format, use a NumberFormat to format your double.

Dilly answered 20/7, 2018 at 17:15 Comment(0)
S
0

As already pointed out by @Nizet, when converting double to string, the output will have scientific notation if number of digits are large. And this is not just for decimals.

Consider:

double d = 1500000000;
System.out.println(String.valueOf(d));

This will print 1.5E9

If you want conversion to happen in readable format, use String.format

System.out.println(String.format ("%.0f", d));

will print 1500000000

Stiles answered 20/7, 2018 at 17:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.