我想确保我了解如何更改字符(主要是将“.”更改为“,”,反之亦然)。
所以我写了一个程序,但我无法输入十进制数。我该怎么办?
import java.text.DecimalFormat;
import javax.swing.*;
public class decimalFormat {
public static void main(String[]args) {
DecimalFormat df= new DecimalFormat("##,##0.00");
String s= JOptionPane.showInputDialog(null,"Please enter a number");
s= df.format(s);
double t=Double.parseDouble(s);
JOptionPane.showMessageDialog(null,"Your number rounded to two digits is");
}
}
最佳答案
您应该使用DecimalFormat.parse()
而不是DecimalFormat.format()
。 parse()
用于将 String
转换为 Number
,format()
用于转换 Number
到 String
。
来自文档:
parse()
: Parses text from the beginning of the given string to produce a number.
format()
: Formats an object to produce a string.
您的代码应如下所示:
DecimalFormat df= new DecimalFormat("##,##0.00");
String s = JOptionPane.showInputDialog(null,"Please enter a number");
double t = df.parse(s).doubleValue();
关于java - java中如何输入小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56305590/