I have a question about big numbers in groovy, I write at script that call to DB and put budget value in variable called toub_start_budget, the value stored is 2570000000. since I want to do arithmetic operation I created another variable called toub_budget and put in it the value of the first variable as float. The problem is that the new variable not saved the data as float but as a number as 2.56999987E9. and the arithmetic that I do are wrong, for example divide by 1000000, will bring 2569.9 and not the accurate results 2570 (accuracy is important). can someone please advise how to handle big numbers, with arithmetic? regards
Asked
Active
Viewed 176 times
-1
-
Use `BigDecimal` instead of `float` – Szymon Stepniak Oct 05 '17 at 09:10
-
1Please do not post images of code and output, but post the text itself indented by four spaces. – Vampire Oct 05 '17 at 09:20
-
You want to spend some serious time learning about fundamentals of floating point numbers... for example https://stackoverflow.com/questions/588004/is-floating-point-math-broken ... and then you read about floating point numbers on the JVM ... – GhostCat Oct 05 '17 at 09:26
1 Answers
2
Do not use float
, it is by definition inaccurate. If you need to do accurate calculations and arbitrary big numbers, use BigDecimal
. If you use Groovy, then just do the calculation, Groovy will automatically use BigDecimal
when appropriate as you can see by executing (2570000000 / 1000).getClass()
and (2570000000 / 1001).getClass()

Vampire
- 35,631
- 4
- 76
- 102