Created
August 23, 2019 11:55
-
-
Save calaveraInfo/b4905e2f99529c7760b1015f34253a90 to your computer and use it in GitHub Desktop.
Floating point hell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigDecimal; | |
import org.junit.jupiter.api.Test; | |
public class Sandbox { | |
@Test | |
public void testFloat() { | |
double raw = 21.05d; | |
double computed = 21.025d+0.025d; | |
double rounded = Math.round((21.025d+0.025d) * 1000d) / 1000d; | |
System.out.println(raw); | |
//21.05 | |
System.out.println(computed); | |
//21.049999999999997 | |
System.out.println(rounded); | |
//21.05 | |
System.out.printf("%.48f\n", raw); | |
//21,050000000000000000000000000000000000000000000000 | |
System.out.printf("%.48f\n", computed); | |
//21,049999999999997000000000000000000000000000000000 | |
System.out.printf("%.48f\n", rounded); | |
//21,050000000000000000000000000000000000000000000000 | |
System.out.println(new BigDecimal(raw)); | |
//21.050000000000000710542735760100185871124267578125 | |
System.out.println(new BigDecimal(computed)); | |
//21.0499999999999971578290569595992565155029296875 | |
System.out.println(new BigDecimal(rounded)); | |
//21.050000000000000710542735760100185871124267578125 | |
System.out.println(Double.valueOf("21.050000000000000710542735760100185871124267578125").doubleValue()); | |
//21.05 | |
} | |
} |
I wish I could do that :(.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
new BigDecimal("21.05")
good luck! :)