简体   繁体   English

在Java中将任何数字字符串(int,float,double,long等)转换为适当的数值(int,float,double,long等)

[英]Convert any number string(int, float, double, long, etc) to appropriate numeric (int, float, double, long, etc) value in java

Is there a better practice to convert any input number string (int, double, etc) to it's respective Wrapper object/primitive type in java? 是否有更好的做法将任何输入数字字符串(int,double等)转换为java中相应的Wrapper对象/原始类型?

Using valueOf() or parseXXX() methods it can achieved. 使用valueOf()parseXXX()方法可以实现。 but I should be knowing the underlying string format before selecting the appropriate type. 但是在选择适当的类型之前,我应该知道底层的字符串格式。

What I am doing is parsing number string to long, using the NumberUtils from commons-lang.jar as follows: 我正在做的是使用commons-lang.jar中NumberUtils数字字符串解析为长整数 ,如下所示:

long longValue= (long) NumberUtils.toLong(numberString);

but the problem is If the numberString has a double value, then it fails to parse to number and will return 0.0 as parsed value. 但是问题是,如果numberString有一个double numberString值,那么它将无法解析为number,并且将返回0.0作为已解析的值。 Only the following statement works fine for double values : 只有以下语句适用于double值:

Long longValue = (long) NumberUtils.toDouble(numberString);

Is there a generic way of doing this? 有通用的方法可以做到这一点吗? also I don't care about the digits after the decimal. 我也不在乎小数点后的数字。

Thanks for reading. 谢谢阅读。

Update 更新资料

This looks elegant solution to me, suggested by @Thomas : @Thomas建议的这对我来说似乎是一种优雅的解决方案:

NumberFormat numberFormat = NumberFormat.getNumberInstance(); long longValue = numberFormat.parse(targetFieldValue).longValue();

as the parse() method returns Long or Double wrapper object, It can be checked and assigned accordingly for generic use. parse()方法返回LongDouble包装器对象时,可以对其进行检查并进行相应分配以用于一般用途。 Only catch here is that the parse() could throw ParseException , so need to be handled according to the requirement. 这里唯一要注意的是parse()可能抛出ParseException ,因此需要根据要求进行处理。

I've used this to solve my problem, but curious to know about any other solutions!! 我已经用它来解决我的问题,但想知道其他解决方案!!

import static org.apache.commons.lang3.math.NumberUtils.isDigits;
import static org.apache.commons.lang3.math.NumberUtils.toDouble;
import static org.apache.commons.lang3.math.NumberUtils.toLong;    

public static void main(String[] args) {
  String numberString = "-23.56";
  long longNumber = (isDigits(numberString) ? toLong(numberString) : (long) toDouble(numberString));
  System.out.println(longNumber);
}

The cast here assumes that you are happy with truncating the decimal, regardless of the sign (the presence of - in the string would mean isDigits returns false ). 此处的isDigits假定您满意于isDigits小数点,而不考虑sign (字符串中存在-表示isDigits返回false )。 If not, do the appropriate rounding. 如果不是,请进行适当的舍入。

If you fear the string might contain alphabets, use the createLong variant that would throw a NumberFormatException instead of defaulting to 0 . 如果您担心字符串可能包含字母,请使用createLong变体,该变体将引发NumberFormatException而不是默认为0

I've needed a more sophisticated approach, since I wanted "1.0" serialized as a double, not as an int so I implemented my own solution and I leave it for the future: 我需要一种更复杂的方法,因为我希望将“ 1.0”序列化为双精度而不是整数,因此我实现了自己的解决方案,并将其留待将来使用:

public Number deserialize(CharSequence text) {
    Preconditions.checkArgument(Objects.requireNonNull(text).length() > 0);

    switch (text.charAt(text.length() - 1)) {
        case 'L':
            return Long.parseLong(text.subSequence(0, text.length() - 1).toString());
        case 'f':
            return Float.parseFloat(text.toString());
        default:
            Number number = Ints.tryParse(text.toString());
            if (number == null) {
                number = Doubles.tryParse(text.toString());
            }
            if (number == null) {
                throw new IllegalArgumentException("Unsupported number: " + text);
            }
            return number;
    }
}

The format follows the way as in Java, so integers without 'L' at the end will be converted to Integers otherwise Longs. 格式遵循Java中的方式,因此末尾没有'L'的整数将转换为Integers,否则将转换为Longs。 Decimal numbers will be converted into Doubles unless they end with 'f' in that case they will be converted to Floats. 十进制数字将转换为Doubles,除非它们以'f'结尾,否则将转换为Floats。 The following tests are passing: 通过了以下测试:

    EXPECT.that(deserialize("1")).isEqualTo(1);
    EXPECT.that(deserialize("5L")).isEqualTo(5L);
    EXPECT.that(deserialize("2.0")).isEqualTo(2.0);
    EXPECT.that(deserialize("4.0f")).isEqualTo(4.0f);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM