1

我想在 Java 中将字符串转换为数字。我已经尝试过两种方法,但都对整数不好,添加了一个不需要的浮点:“1”> 1.0(当我想要“1”> 1 和“1.5”> 1.5 时)。我发现了更多将字符串转换为数字的方法,但它们要么不起作用,要么行数很多,我不敢相信它来自我只需要 parseFloat() 的 javascript 如此复杂。

这就是我现在正在尝试的:

String numString = "1".trim().replaceAll(",","");
float num = (Float.valueOf(numString)).floatValue(); // First try
Double num2 = Double.parseDouble(numString); // Second try
System.out.println(num + " - " + num2); // returns 1.0 - 1.0

我怎样才能只在需要时使用浮点数?

4

3 回答 3

3

要根据需要格式化浮点数,请使用DecimalFormat

DecimalFormat df = new DecimalFormat("#.###");
System.out.println(df.format(1.0f)); // prints 1
System.out.println(df.format(1.5f)); // prints 1.5

在你的情况下,你可以使用

System.out.println(df.format(num) + " - " + df.format(num2));
于 2012-12-29T19:42:29.077 回答
1

我想你要找的是DecimalFormat

DecimalFormat format = new DecimalFormat("#.##");
double doubleFromTextField = Double.parseDouble(myField.getText());
System.out.println(format.format(doubleFromTextField));
于 2012-12-29T19:43:21.783 回答
0

问题在于您的问题实际上是一种类型安全的语言,我认为您正在混合转换和字符串表示。在 Java 或 C# 或 C++ 中,您转换为某些可预测/预期的类型,看起来就像您期望在 JavaScript 中习惯的“变体”行为。

您可以使用类型安全的语言执行以下操作:

public static Object convert(String val)
{
  // try to convert to int and if u could then return Integer
  ELSE
  //try to convert to float and if you could then return it
  ELSE
  //try to convert to double
  etc...
}

当然,这是非常低效的,就像 JavaScript 与 C++ 或 Java 相比一样。变体/多态性(使用对象)是有代价的

然后你可以做 toString() 将整数格式化为整数,浮点数为浮点数,双倍多态。但是您的问题充其量是模棱两可的,这使我相信存在概念问题。

于 2012-12-29T19:45:44.850 回答