double displaying very long number

后端 未结 4 596
我寻月下人不归
我寻月下人不归 2021-01-15 00:14

I have a simple calculation that uses doubles but I\'m getting an unexpected result and I can\'t understand why?

import java.util.Scanner;
public class Versa         


        
4条回答
  •  走了就别回头了
    2021-01-15 00:51

    Doubles (floating-point values in general) cannot always represent exactly what we think of intuitively as a precise value. This is because of the way in which floats are stored, and can vary from machine to machine and language to language. When you try to store 2.99, the actual value that is stored may be very slightly different (e.g. 2.990000000000002). This question gives a decent, quick overview of why.

    You should therefore (as it says through the link) never use floating-point primitives to represent currency. Either use BigDecimal, or keep track of two integers yourself (e.g. int dollars; and int cents;).

提交回复
热议问题