Java中将字符串转换为数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41813533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:42:05  来源:igfitidea点击:

Converting String to Number in Java

javaprimitive-types

提问by Lakshan Prabhu

How can i convert a string to a abstract number, provided string is any valid number in java (say int, long, double etc).

我如何将字符串转换为抽象数字,前提是字符串是 java 中的任何有效数字(例如 int、long、double 等)。

I will not know the type of number in the string, so i can't use specific primitive parsing (like Integer.parseInt, Long.parseLong etc). Is there any generic way to convert it?

我不会知道字符串中数字的类型,所以我不能使用特定的原始解析(如 Integer.parseInt、Long.parseLong 等)。有没有通用的方法来转换它?

Eg:

例如:

  • String -> Number
  • "23423" -> 23423
  • "34.3" -> 34.3
  • "45364573747546" -> 45364573747546
  • 字符串 -> 数字
  • “23423”-> 23423
  • “34.3”-> 34.3
  • “45364573747546”-> 45364573747546

采纳答案by minigeek

Use NumberFormat. Number cannot be instantiated because it is an abstract class.

使用数字格式。Number 不能被实例化,因为它是一个抽象类。

 Number number = NumberFormat.getInstance().parse(string);

回答by sssemil

Double.valueOf()will do fine unless you have a very long number.

Double.valueOf()除非你有一个很长的数字,否则会很好。

回答by Code-Apprentice

The quickest way to do this is just always use Double.parseDouble(). If you need a general-purpose parser that determines which primitive to use, rather than always using the same type, then you will need to write your own. One way to do this is to use each parseXxx()method and lot of try...catchstatements.

执行此操作的最快方法是始终使用Double.parseDouble(). 如果您需要一个通用解析器来确定要使用哪个原语,而不是总是使用相同的类型,那么您将需要编写自己的解析器。一种方法是使用每种parseXxx()方法和大量try...catch语句。

回答by Noureddine Ouertani

For integers:

对于整数:

int myInteger = Integer.parseInt("23423");

For doubles:

对于双打:

double myDouble = Double.parseDouble("34.3");

回答by Olivier Grégtheitroade

Doublewill make your value lose precision if too long.

Double如果太长,会使您的值失去精度。

You should use a BigDecimalinstead:

您应该使用 aBigDecimal代替:

BigDecimal number = new BigDecimal("43.256");

You can then get different primitives like this:

然后,您可以获得不同的原语,如下所示:

try {
  int intValue = number.intValueExact();
} catch (ArithmeticException e) {
  try {
    long longValue = number.longValueExact();
  } catch (ArithmeticException e) {
    double doubleValue = number.doubleValue();
  }
}

回答by Arsen Alexanyan

As long as your strings could be big numbers (suppose that no longer than primitive long and double), then generic way could be decide whether it is long or double.

只要您的字符串可能是大数字(假设不超过原始 long 和 double),那么通用方式就可以决定它是 long 还是 double。

Number n = Double.valueOf(string);
if((double)n.intValue() == n.doubleValue()){
   //n is double use n.doubleValue() or just use the n for generic purposes
}
else{
   //n is int use n.intValue() or just use the n for generic purposes
}

回答by Sandeep

Two cases:

两种情况:

  1. If you input string is less than 8 Bytes:
  1. 如果输入的字符串小于 8 字节:

double primitiveNumber = Double.parseDouble(input);

double primitiveNumber = Double.parseDouble(input);

  1. If Your input string is more than 8 bytes: you anyway cannot store it in a primitive, Then you can go with Number class, but this is not likely to happen since you expect a primitive.
  1. 如果您的输入字符串超过 8 个字节:无论如何您都无法将其存储在原语中,那么您可以使用 Number 类,但这不太可能发生,因为您希望使用原语。

回答by ravip

I do prefer BigDecimalonly. Because it won't have the issues with size and precision

BigDecimal只喜欢。因为它不会有尺寸和精度的问题

回答by Varejones

You can use Double.parseDouble()to convert your string to double. This will work even if the string is an integer:

您可以使用Double.parseDouble()将字符串转换为双精度。即使字符串是整数,这也会起作用:

String myString = "1234.56";
double myDouble = Double.parseDouble(myString);

If you need to check if it is an integer or a double:

如果您需要检查它是整数还是双精度数:

String myString = "1234.56";
int myInt;
double myDouble = Double.parseDouble(myString);
if ((myDouble % 1) == 0) {
   myInt = (int) myDouble;
   System.out.println("myString is an integer: " + myInt );       
} else {
   System.out.println("myString is a double: " + myDouble );    
}

Or you can use Guava'sDoubleMath.isMathematicalInteger():

或者你可以使用番石榴的DoubleMath.isMathematicalInteger()

String myString = "1234.56";
int myInt;
double myDouble = Double.parseDouble(myString);
if (DoubleMath.isMathematicalInteger(myDouble)) {
   myInt = (int) myDouble;
   System.out.println("myString is an integer: " + myInt );       
} else {
   System.out.println("myString is a double: " + myDouble );    
}