Separating double into integer and decimal parts

前端 未结 11 1073
日久生厌
日久生厌 2020-12-06 10:20

I am trying to separate a double into the integer and decimal parts

So for example, the number 24.4 should be separated into 24 and 4.

int integer =          


        
11条回答
  •  猫巷女王i
    2020-12-06 10:57

    This is because doubles aren't exactly "real numbers" - remember there are infinite number of real numbers in any range, while there are only finite number of digits in double - thus finite number of values, so some round off must occure.

    The fact is, 24.4 cannot be exactly represented by double - so the fraction of your number really is something around 0.3999....
    If you want an exact solution - you should use a library that gives you exact values for decimals, such as BigDecimal.

    If you want to understand more about this issue of doubles being not exact - you should read more about floating points arithmetics, and this article, though high level, is also a must in order to really understand what's going on.

    If you cannot understand these article just yet - just take into consideration: If you need an exact value - doubles cannot provide it - and you should use a library if this is the case.

提交回复
热议问题