简体   繁体   中英

Precision error when parsing a double variable using StringTokenizer in Java

I'm using the StringTokenizer class to read a text file. In the text file, there's a couple of double values.

interest = Double.parseDouble(aString.nextToken());
System.out.println(interest);

It shows up fine in the console, however when I try to print it later,

System.out.println("Fixed Daily Interest = " + customers[i].get_interest() + "\n");

Precision is always lost by a decimal point. For example one of the values is 0.055, when I print it after I parse it in the first part of the code, it shows up exactly as that in the console. However in another method, trying to print it gives me 0.05, no matter what I try, not parsing it as a double variable, using DecimalFormat, etc. Would any kind soul guide me what's the mistake I'm making here? I'm really perplexed here.

You could use DecimalFormat to get precision in Java.

Reading a bit more on this found this post which might give you some pointers. Basically, if you need more precision, you will need to move onto a specially designed class that handles this. The post lists several options.

Try using BigDecimal if you requires extra precision. If the problem is reading a double value and then printing outputs a different value, remember the problem of binary <-> decimal number representations. Some decimal numbers can't be represented in a binary format with limited binary precision. Also when operating with numbers, the result can be printed sometimes as 4,99997 instead of decimal 5, the problem is with the representation of this numbers in binary.

Ensure the number is never touched, then the output of printing it must be always the same, if you use toString() or directly in System.out.println("" + number); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM