如何在Java中输入小数

时间:2019-05-25 14:09:47

标签: java decimalformat

我想确保我了解如何将字符(主要是从“。”更改为“,”,反之亦然)进行更改。

所以我写了一个程序,但是我不能输入十进制数。我该怎么办?

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");
    }
}

1 个答案:

答案 0 :(得分:0)

您应该使用DecimalFormat.parse()而不是DecimalFormat.format()parse()用于将String转换为Numberformat()用于将Number转换为String

从文档中

  

parse() :从给定字符串的开头解析文本以产生数字。

     

format() :格式化对象以产生字符串。

您的代码应如下所示:

DecimalFormat df= new DecimalFormat("##,##0.00");
String s = JOptionPane.showInputDialog(null,"Please enter a number");
double t = df.parse(s).doubleValue();