开发者

How to avoid Double values getting stored in 1Ex format?

I am having a double variable:

private double b=0.0;

I am taking value of a certain field in b (the value is between 0.0 to 9.99999999). Mostly, user enters value between 0.0 to 1.0.

When I a开发者_如何学编程m saving the value from user in 'b', and if the value is 0.000001, then it is getting saved as 1E-6 and next time displayed as same on the screen (this is because b is Double).

Is there any way (just by calling some method) in Java, that I can avoid the conversion of value to 1E-6 format? I want to save the value as entered by user only (0.000001).


The double isn't actually "saved" as a string at all. That's just a matter of formatting - for which you should see DecimalFormat. However, it definitely won't be exactly 0.000001 because that number isn't exactly representable as a double. I would strongly recommend that you use BigDecimal instead when precise decimal values matter (as it sounds like they do here).


It's true that the number isn't stored in memory using the scientific (E) notation.

You can demonstrate this to yourself by formatting the number differently when you output it:

@Test
public void testLittle() {
    double myNum = 0.000001;
    System.out.printf("%f \n",myNum);
}

You should definitely heed other advice posted in answers here and use BigDecimal if you really want the output to match the input, since some floating-point values aren't what you think they are when representing them in a computer. (ref: IEEE-754)

The "Java Puzzlers" presentations sometimes discuss these odd behaviors and are always a fun way to learn. (See this talk from Google I/O 2011, a bit after 3 minutes in)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜