【问题标题】:Formatting double as a function parameter将 double 格式化为函数参数
【发布时间】:2020-09-06 16:50:43
【问题描述】:

我有一个函数,它接受一个双精度作为参数。但是,如果我在调用函数时输入“8”,它会处理为“8.0”。

我知道我可以用String.format()和其他方法格式化它,但是输入数字的格式对结果很重要(8与8.0的结果不同,我不知道函数内部body 是用户想要的)。

我知道我可以添加一个格式参数以及双精度参数function(double d, DecimalFormat f),但这会使其使用起来更加乏味,而且无论如何它都是用作 util 函数。有什么建议吗?

【问题讨论】:

  • Formattong 把它变成一个字符串。真正的问题是什么?为什么 8 和 8.0 的答案不同?函数的目的是什么?
  • 也许有点背景/真实案例可能会有所帮助:-)
  • if I input "8" when I call the function, it processes as "8.0" -- 不,它没有;它将其作为IEEE 754 double-precision binary floating-point format 处理。 8.0 是一种显示表示;您可以使该浮点数在显示时以任何您想要的方式显示。
  • “输入数字的格式对结果很重要” 为什么?!? 88.08e0800e-2、...都表示同一个数值,即8。数字没有格式,所以格式不能是“重要的”。
  • @Andreas 我们不知道 OP 实际上在做什么,但是 8 和 8.0 的 precision 是不同的——这可能是 OP 试图传达的内容.也许吧。

标签: java number-formatting


【解决方案1】:

有一些方法可以解决这个问题,具体取决于您的问题。

  1. 方法重载

如果用户通过代码输入,你可以使用相同的方法名来处理不同的类型。

class Program {
    public static void foo(int n) {
        // The input is an integer
        System.out.println(n);
    }

    public static void foo(double x) {
        // The input is a double
        System.out.println(x);
    }

    public static void main(String[] args) {
        foo(8); // prints 8
        foo(8.0); // prints 8.0
    }
}
  1. 处理字符串

但是,如果用户通过键盘输入,例如,您可以使用 RegEx。

class Program {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String input = s.nextLine();

        if (input.matches("^\\d+\\.\\d+$")) {
            // The input is a double
        } else if (input.matches("\\d+")) {
            // The input is an integer
        } else {
            // The input is something else
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-30
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多