This question has already been answered:

There are integer and fractional. How to multiply them among themselves to get an accurate result. The variant with BigDecimal and Math.round () is not considered. Are there any other means for such calculations (without that.to pass the numbers to the constructor of the BigDecimal class. Without these dances with a tambourine)? Can the use of third-party libraries or other language tools? Here is an example: 24 * 0.05 = 1.2000000000000002 As we see the correct answer here is definitely 24 * 0.05 = 1.2. As in this case, get 1.2, not 1.20000000000002

Reported as a duplicate by participants Alexey Shimansky , zRrr , aleksandr barakin , user194374, PashaPash Jun 16 '16 at 11:12 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • 2
    Look at the answer in the duplicate above, why fractional numbers behave this way. And as a result - it is rather necessary to use rounding than not to use) - Alexey Shimansky
  • The question is a little different. are there any means to circumvent this phenomenon without using pieces like BigDecimal (because it slows down the calculations) - Iga
  • um .. 24*0.05f ? - Alexey Shimansky
  • OK. I want to count 2147483647f * 6f. Idea says: 1.2884901888E10. this is not good ( - Iga
  • during calculations, the environment will always count these numbers as float. If I go beyond the float range, how will it behave? - Iga

1 answer 1

The accuracy of operations with fractional numbers (floating point) is guaranteed only to some extent. Any library or calculator is rounded to some mark. 1.2000000000000002 if to round off, it turns out 1.2 1.9999999999999999 will turn out 2

Of course, you can transfer a fractional number to an integer, multiply. then share ... but it is not effective. I am advised that 1.25 * 2 = 125 * 2/100. Better right away

I recommend choosing the number of decimal places.

 new BigDecimal(String.valueOf(double)).setScale(yourScale, BigDecimal.ROUND_HALF_UP); 
  • the BigDecimal class is good, but as I understand it, calculations are slower. I'm trying to understand whether it is possible to perform serious computations in java painlessly (without any bigdecimal), or better to develop an engine for the game, or is it better to charge C ++ in which, without any whistles and roundings, the desired result is obtained by standard means - Iga