java - java中如何输入小数

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

最佳答案

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

来自文档:

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/

相关文章:

java - 如何使用 DecimalFormat 仅隐藏数字 "with decimals"中的尾随零

r - 在 R 中用点作为千位分隔符加载 csv 的最优雅的方法

java - 如何使用 spring IDE 查看 spring 项目的类图

java - 使用较新 Java 的 Elasticsearch 占用的 RAM 比应有的要多

java - json org.json.JSONException : Missing ';' in XML entity 中的 xml 解码问题

java - 无法在jenkins中执行java程序?

java - 如何在获取百分比符号时避免 UnsupportedOperationException?

java - DecimalFormatting double 的语法

java - 为什么 Math.floor(1.23456789 * 1e8)/1e8) 返回 1.23456788

java - play 2.0 如何定义具有多个按键的取景器