Requirements: convert string (the string only has one decimal) to float to perform calculations, convert the result into a string (retain one decimal)
Directly upload the code:
float f1 = 0.1f;String a1 = "1.5";System.out.println(Float.parseFloat(a1)+f1);
Answer: 1.6
float f1 = 0.1f;String a1 = "1.6";System.out.println(Float.parseFloat(a1)+f1);
Answer: 1.7
To be honest, at the beginning I felt that the code was fine. I tried a lot of strings from 0.1, but all of them were correct.
However, when a1 = "1.7", the problem arises, the output result: 1.8000001
Um? Is there a problem with the conversion method? It’s a routine to wander around the Internet for a long time.
This can only be considered from the number of retained digits and accuracy. So I discovered DecimalFormat
0 A number
# A number, not including 0
. Placeholder for decimal separator
, placeholder for group delimiter
; Delimited format.
- Default negative prefix.
% multiplied by 100 and displayed as percentage
float f = 0.1f;String max ="1.7";DecimalFormat df = new DecimalFormat("########.#");String s = df.format(Float.parseFloat(max)+f);System.out.println(s);Results: 1.8
OK, problem solved!
The above method of Java string to float operation to float is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.