Java 数字格式未给出正确的数字
我有以下代码:Java 数字格式未给出正确的数字,java,Java,我有以下代码: import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; import java.util.Scanner; class EntryPoint { static Locale czech = null; static Locale getCzechLocale(){ if (czech == null){
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
import java.util.Scanner;
class EntryPoint {
static Locale czech = null;
static Locale getCzechLocale(){
if (czech == null){
czech = new Locale("cs","CZ");
}
return czech;
}
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
NumberFormat nf = NumberFormat.getInstance(getCzechLocale());
System.out.println(nf.format(12000.5));
NumberFormat nf2 = NumberFormat.getCurrencyInstance(getCzechLocale());
try {
String input = sn.nextLine();
System.out.println(input);
Number n = nf.parse(input);
System.out.println(n.floatValue());
}catch(ParseException javaTextParseException){
System.err.println("Unable to parse input String");
}
}
}
我想归档这个东西:如果我输入数字“12000,5”(就像程序显示一样)程序解析和这个字符串,将显示数字“12000.5”。
我怎么了?
现在如果我输入“12000,5”而不输入“sign program display float number”12.0而不是“12000.5”
已解决
NumberFormat.Parse(字符串)将在第一个空格字符处结束,所以如果我使用trim()并替换(“,”),则结果是正确的。试试这段代码,它对我很有用:
Locale czech = new Locale("cs", "CZ");
Scanner sn = new Scanner(System.in);
NumberFormat nf = NumberFormat.getInstance(czech);
String input = sn.nextLine();
System.out.println(nf.format(Double.parseDouble(input)));
sn.close();
如果您使用的是固定格式,如
NumberFormat nf = new DecimalFormat("### ###.##");
Number n=nf.parse("123 456,78");
NumberFormat不会停留在第一个空格上,只是您正在使用的NumberFormat所使用的分组分隔符是一个不间断的空格,而不是一个常规空格 如果您复制并粘贴程序的输出以将其作为输入传递,它将很高兴地将其解析回12000.5,因为输出使用非中断空间 如果希望它使用常规空格字符,请使用
DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(new Locale("cs", "CZ"));
DecimalFormatSymbols decimalFormatSymbols = nf.getDecimalFormatSymbols();
decimalFormatSymbols.setGroupingSeparator(' ');
nf.setDecimalFormatSymbols(decimalFormatSymbols);
为什么你认为这是错误的?我在系统上使用“en_US”区域设置,所以我需要以“cs_CZ”格式输入文本并以“en_US”@Henry显示,因为如果我输入“12000,5”,我的结果是“12.0”“不为我工作:/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/bin/Java-Dfile.encoding=UTF-8-jar/Users/jvalek/IdeaProjects/HelloWorld/out/artifacts/HelloWorld_jar/HelloWorld.jar 12 000,5线程”main“Java.lang.NumberFormatException”中的异常:输入字符串:“12 000,5”在sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043)在sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)在java.lang.Double.parseDouble(Double.java:538)在EntryPoint.main(EntryPoint.java:22)处理完成,退出代码为1您无需自己输入12000,5,您只需输入12000.5,其余的代码将由上面的代码完成。