简体   繁体   English

JAVA双精度字符串格式

[英]JAVA double to string format

Suddenly I get an error which before I didnt have 突然我收到一个错误,之前我没有

Example: 例:

Double double1 = 0.12;
String string1 = String.format("%.2f", double1)

System.out.println(string1);

Output: 输出:

0,12

Then I do this 那我做

double double2 = Double.parseDouble(string1);

Error 错误

java.lang.NumberFormatException: For input string: "0,12"

I'm pretty sure I comes because of the "," (comma). 我很确定我是因为“,”(逗号)而来的。 The funny thing is that two days ago anything was working fine and I didnt change anything. 有趣的是,两天前一切正常,我没有做任何更改。

Do know what happened or what I need to change? 是否知道发生了什么或我需要更改什么?

Double#parseDouble parses numbers in the format out put by Double#toString . Double#parseDoubleDouble#toString输出的格式解析数字。

String#format , when asked to format a number with a decimal point, will output this in the current locale, but Double#toString will not. 当要求使用String#format格式化带小数点的数字时,它将在当前语言环境中输出,但Double#toString不会。

If you want to parse the output of String#format , I believe that Scanner can do this. 如果您想解析String#format的输出,我相信Scanner可以做到这一点。 Personally, though, I would avoid localisation in numbers you expect to parse, and either use Double#toString to do the formatting, or explicitly pass Locale.ROOT when formatting it. 但是,就我个人而言,我会避免对您希望解析的数字进行本地化,而是使用Double#toString进行格式化,或者在格式化时显式传递Locale.ROOT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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