Skip to content

Instantly share code, notes, and snippets.

@calaveraInfo
Created August 23, 2019 11:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calaveraInfo/b4905e2f99529c7760b1015f34253a90 to your computer and use it in GitHub Desktop.
Save calaveraInfo/b4905e2f99529c7760b1015f34253a90 to your computer and use it in GitHub Desktop.
Floating point hell
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
}
}
@saberduck
Copy link

new BigDecimal("21.05")
good luck! :)

@calaveraInfo
Copy link
Author

I wish I could do that :(.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment