The accuracy of a double in general programming and Java

后端 未结 2 1717
独厮守ぢ
独厮守ぢ 2020-12-11 08:47

I understand that due to the nature of a float/double one should not use them for precision important calculations. However, i\'m a little confused on their limitations due

相关标签:
2条回答
  • 2020-12-11 09:29

    I suggest you read this page:
    https://en.wikipedia.org/wiki/Double-precision_floating-point_format

    Once you've read and understood it, and perhaps converted several examples to their binary representations in the 64 bit floating point format, then you'll have a much better idea of what significant digits a Double can hold.

    0 讨论(0)
  • 2020-12-11 09:33

    As a side note, (perhaps trivial) a nice and reliable way to store a known precision of value is to simply multiply it by the relevant factor and store as some integral type, which are completely precise.

    For example:

    double costInPounds = <something>; //e.g. 3.587
    int costInPence = (int)(costInPounds * 100 + 0.5); //359
    

    Plainly some precision can be lost, but if a required/desired precision is known, this can save a lot of bother with floating point values, and once this has been done, no precision can be lost by further manipulations.

    The + 0.5 is to ensure that rounding works as expected. (int) takes the 'floor' of the provided double value, so adding 0.5 makes it round up and down as expected.

    0 讨论(0)
提交回复
热议问题