File: FloatCast.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (21 lines) | stat: -rw-r--r-- 634 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Casts have higher precedence than binary expressions, so `(int) 0.5f * 100` is
equivalent to `((int) 0.5f) * 100` = `0 * 100` = `0`, not `(int) (0.5f * 100)` =
`50`.

To avoid this common source of error, add explicit parentheses to make the
precedence explicit. For example, instead of this:

```java
long SIZE_IN_GB = (long) 1.5 * 1024 * 1024 * 1024; // this is 1GB, not 1.5GB!

// this is 0, not a long in the range [0, 1000000000]
long rand = (long) new Random().nextDouble() * 1000000000
```

Prefer:

```java
long SIZE_IN_GB = (long) (1.5 * 1024 * 1024 * 1024);

long rand = (long) (new Random().nextDouble() * 1000000000);
```