
fr.ght1pc9kc.juery.basic.common.lang3.NumberUtils Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.ght1pc9kc.juery.basic.common.lang3;
import java.math.BigDecimal;
import java.math.BigInteger;
public class NumberUtils {
/**
* Checks whether the String a valid Java number.
*
* Valid numbers include hexadecimal marked with the {@code 0x} or
* {@code 0X} qualifier, octal numbers, scientific notation and
* numbers marked with a type qualifier (e.g. 123L).
*
* Non-hexadecimal strings beginning with a leading zero are
* treated as octal values. Thus the string {@code 09} will return
* {@code false}, since {@code 9} is not a valid octal value.
* However, numbers beginning with {@code 0.} are treated as decimal.
*
* {@code null} and empty/blank {@code String} will return
* {@code false}.
*
* Note, {@link #createNumber(String)} should return a number for every
* input resulting in {@code true}.
*
* @param str the {@code String} to check
* @return {@code true} if the string is a correctly formatted number
* @since 3.5
*/
public static boolean isCreatable(final String str) {
if (StringUtils.isEmpty(str)) {
return false;
}
final char[] chars = str.toCharArray();
int sz = chars.length;
boolean hasExp = false;
boolean hasDecPoint = false;
boolean allowSigns = false;
boolean foundDigit = false;
// deal with any possible sign up front
final int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0;
if (sz > start + 1 && chars[start] == '0' && !StringUtils.contains(str, '.')) { // leading 0, skip if is a decimal number
if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0X
int i = start + 2;
if (i == sz) {
return false; // str == "0x"
}
// checking hex (it can't be anything else)
for (; i < chars.length; i++) {
if ((chars[i] < '0' || chars[i] > '9')
&& (chars[i] < 'a' || chars[i] > 'f')
&& (chars[i] < 'A' || chars[i] > 'F')) {
return false;
}
}
return true;
} else if (Character.isDigit(chars[start + 1])) {
// leading 0, but not hex, must be octal
int i = start + 1;
for (; i < chars.length; i++) {
if (chars[i] < '0' || chars[i] > '7') {
return false;
}
}
return true;
}
}
sz--; // don't want to loop to the last char, check it afterwords
// for type qualifiers
int i = start;
// loop to the next to last char or to the last char if we need another digit to
// make a valid number (e.g. chars[0..5] = "1234E")
while (i < sz || i < sz + 1 && allowSigns && !foundDigit) {
if (chars[i] >= '0' && chars[i] <= '9') {
foundDigit = true;
allowSigns = false;
} else if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
hasDecPoint = true;
} else if (chars[i] == 'e' || chars[i] == 'E') {
// we've already taken care of hex.
if (hasExp) {
// two E's
return false;
}
if (!foundDigit) {
return false;
}
hasExp = true;
allowSigns = true;
} else if (chars[i] == '+' || chars[i] == '-') {
if (!allowSigns) {
return false;
}
allowSigns = false;
foundDigit = false; // we need a digit after the E
} else {
return false;
}
i++;
}
if (i < chars.length) {
if (chars[i] >= '0' && chars[i] <= '9') {
// no type qualifier, OK
return true;
}
if (chars[i] == 'e' || chars[i] == 'E') {
// can't have an E at the last byte
return false;
}
if (chars[i] == '.') {
if (hasDecPoint || hasExp) {
// two decimal points or dec in exponent
return false;
}
// single trailing decimal point after non-exponent is ok
return foundDigit;
}
if (!allowSigns
&& (chars[i] == 'd'
|| chars[i] == 'D'
|| chars[i] == 'f'
|| chars[i] == 'F')) {
return foundDigit;
}
if (chars[i] == 'l'
|| chars[i] == 'L') {
// not allowing L with an exponent or decimal point
return foundDigit && !hasExp && !hasDecPoint;
}
// last character is illegal
return false;
}
// allowSigns is true iff the val ends in 'E'
// found digit it to make sure weird stuff like '.' and '1E-' doesn't pass
return !allowSigns && foundDigit;
}
//-----------------------------------------------------------------------
// must handle Long, Float, Integer, Float, Short,
// BigDecimal, BigInteger and Byte
// useful methods:
// Byte.decode(String)
// Byte.valueOf(String, int radix)
// Byte.valueOf(String)
// Double.valueOf(String)
// Float.valueOf(String)
// Float.valueOf(String)
// Integer.valueOf(String, int radix)
// Integer.valueOf(String)
// Integer.decode(String)
// Integer.getInteger(String)
// Integer.getInteger(String, int val)
// Integer.getInteger(String, Integer val)
// Integer.valueOf(String)
// Double.valueOf(String)
// new Byte(String)
// Long.valueOf(String)
// Long.getLong(String)
// Long.getLong(String, int)
// Long.getLong(String, Integer)
// Long.valueOf(String, int)
// Long.valueOf(String)
// Short.valueOf(String)
// Short.decode(String)
// Short.valueOf(String, int)
// Short.valueOf(String)
// new BigDecimal(String)
// new BigInteger(String)
// new BigInteger(String, int radix)
// Possible inputs:
// 45 45.5 45E7 4.5E7 Hex Oct Binary xxxF xxxD xxxf xxxd
// plus minus everything. Prolly more. A lot are not separable.
/**
* Turns a string value into a java.lang.Number.
*
* If the string starts with {@code 0x} or {@code -0x} (lower or upper case) or {@code #} or {@code -#}, it
* will be interpreted as a hexadecimal Integer - or Long, if the number of digits after the
* prefix is more than 8 - or BigInteger if there are more than 16 digits.
*
* Then, the value is examined for a type qualifier on the end, i.e. one of
* {@code 'f', 'F', 'd', 'D', 'l', 'L'}. If it is found, it starts
* trying to create successively larger types from the type specified
* until one is found that can represent the value.
*
* If a type specifier is not found, it will check for a decimal point
* and then try successively larger types from {@code Integer} to
* {@code BigInteger} and from {@code Float} to
* {@code BigDecimal}.
*
*
* Integral values with a leading {@code 0} will be interpreted as octal; the returned number will
* be Integer, Long or BigDecimal as appropriate.
*
*
* Returns {@code null} if the string is {@code null}.
*
* This method does not trim the input string, i.e., strings with leading
* or trailing spaces will generate NumberFormatExceptions.
*
* @param str String containing a number, may be null
* @return Number created from the string (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Number createNumber(final String str) {
if (str == null) {
return null;
}
if (StringUtils.isBlank(str)) {
throw new NumberFormatException("A blank string is not a valid number");
}
// Need to deal with all possible hex prefixes here
final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"};
int pfxLen = 0;
for (final String pfx : hex_prefixes) {
if (str.startsWith(pfx)) {
pfxLen += pfx.length();
break;
}
}
if (pfxLen > 0) { // we have a hex number
char firstSigDigit = 0; // strip leading zeroes
for (int i = pfxLen; i < str.length(); i++) {
firstSigDigit = str.charAt(i);
if (firstSigDigit == '0') { // count leading zeroes
pfxLen++;
} else {
break;
}
}
final int hexDigits = str.length() - pfxLen;
if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // too many for Long
return createBigInteger(str);
}
if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // too many for an int
return createLong(str);
}
return createInteger(str);
}
final char lastChar = str.charAt(str.length() - 1);
String mant;
String dec;
String exp;
final int decPos = str.indexOf('.');
final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present
// if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE)
// and the parsing which will detect if e or E appear in a number due to using the wrong offset
if (decPos > -1) { // there is a decimal point
if (expPos > -1) { // there is an exponent
if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE
throw new NumberFormatException(str + " is not a valid number.");
}
dec = str.substring(decPos + 1, expPos);
} else {
dec = str.substring(decPos + 1);
}
mant = getMantissa(str, decPos);
} else {
if (expPos > -1) {
if (expPos > str.length()) { // prevents double exponent causing IOOBE
throw new NumberFormatException(str + " is not a valid number.");
}
mant = getMantissa(str, expPos);
} else {
mant = getMantissa(str);
}
dec = null;
}
if (!Character.isDigit(lastChar) && lastChar != '.') {
if (expPos > -1 && expPos < str.length() - 1) {
exp = str.substring(expPos + 1, str.length() - 1);
} else {
exp = null;
}
//Requesting a specific type..
final String numeric = str.substring(0, str.length() - 1);
final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
switch (lastChar) {
case 'l':
case 'L':
if (dec == null
&& exp == null
&& (!numeric.isEmpty() && numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) {
try {
return createLong(numeric);
} catch (final NumberFormatException nfe) { // NOPMD
// Too big for a long
}
return createBigInteger(numeric);
}
throw new NumberFormatException(str + " is not a valid number.");
case 'f':
case 'F':
try {
final Float f = createFloat(str);
if (!(f.isInfinite() || f.floatValue() == 0.0F && !allZeros)) {
//If it's too big for a float or the float value = 0 and the string
//has non-zeros in it, then float does not have the precision we want
return f;
}
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
//$FALL-THROUGH$
case 'd':
case 'D':
try {
final Double d = createDouble(str);
if (!(d.isInfinite() || d.floatValue() == 0.0D && !allZeros)) {
return d;
}
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
try {
return createBigDecimal(numeric);
} catch (final NumberFormatException e) { // NOPMD
// ignore the bad number
}
//$FALL-THROUGH$
default:
throw new NumberFormatException(str + " is not a valid number.");
}
}
//User doesn't have a preference on the return type, so let's start
//small and go from there...
if (expPos > -1 && expPos < str.length() - 1) {
exp = str.substring(expPos + 1, str.length());
} else {
exp = null;
}
if (dec == null && exp == null) { // no decimal point and no exponent
//Must be an Integer, Long, Biginteger
try {
return createInteger(str);
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
try {
return createLong(str);
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
return createBigInteger(str);
}
//Must be a Float, Double, BigDecimal
final boolean allZeros = isAllZeros(mant) && isAllZeros(exp);
try {
final Float f = createFloat(str);
final Double d = createDouble(str);
if (!f.isInfinite()
&& !(f.floatValue() == 0.0F && !allZeros)
&& f.toString().equals(d.toString())) {
return f;
}
if (!d.isInfinite() && !(d.doubleValue() == 0.0D && !allZeros)) {
final BigDecimal b = createBigDecimal(str);
if (b.compareTo(BigDecimal.valueOf(d.doubleValue())) == 0) {
return d;
}
return b;
}
} catch (final NumberFormatException nfe) { // NOPMD
// ignore the bad number
}
return createBigDecimal(str);
}
//-----------------------------------------------------------------------
/**
* Convert a {@code String} to a {@code Float}.
*
* Returns {@code null} if the string is {@code null}.
*
* @param str a {@code String} to convert, may be null
* @return converted {@code Float} (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Float createFloat(final String str) {
if (str == null) {
return null;
}
return Float.valueOf(str);
}
/**
* Convert a {@code String} to a {@code Double}.
*
* Returns {@code null} if the string is {@code null}.
*
* @param str a {@code String} to convert, may be null
* @return converted {@code Double} (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Double createDouble(final String str) {
if (str == null) {
return null;
}
return Double.valueOf(str);
}
/**
* Convert a {@code String} to a {@code Integer}, handling
* hex (0xhhhh) and octal (0dddd) notations.
* N.B. a leading zero means octal; spaces are not trimmed.
*
* Returns {@code null} if the string is {@code null}.
*
* @param str a {@code String} to convert, may be null
* @return converted {@code Integer} (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Integer createInteger(final String str) {
if (str == null) {
return null;
}
// decode() handles 0xAABD and 0777 (hex and octal) as well.
return Integer.decode(str);
}
/**
* Convert a {@code String} to a {@code Long};
* since 3.1 it handles hex (0Xhhhh) and octal (0ddd) notations.
* N.B. a leading zero means octal; spaces are not trimmed.
*
* Returns {@code null} if the string is {@code null}.
*
* @param str a {@code String} to convert, may be null
* @return converted {@code Long} (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static Long createLong(final String str) {
if (str == null) {
return null;
}
return Long.decode(str);
}
/**
* Convert a {@code String} to a {@code BigInteger};
* since 3.2 it handles hex (0x or #) and octal (0) notations.
*
* Returns {@code null} if the string is {@code null}.
*
* @param str a {@code String} to convert, may be null
* @return converted {@code BigInteger} (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static BigInteger createBigInteger(final String str) {
if (str == null) {
return null;
}
int pos = 0; // offset within string
int radix = 10;
boolean negate = false; // need to negate later?
if (str.startsWith("-")) {
negate = true;
pos = 1;
}
if (str.startsWith("0x", pos) || str.startsWith("0X", pos)) { // hex
radix = 16;
pos += 2;
} else if (str.startsWith("#", pos)) { // alternative hex (allowed by Long/Integer)
radix = 16;
pos++;
} else if (str.startsWith("0", pos) && str.length() > pos + 1) { // octal; so long as there are additional digits
radix = 8;
pos++;
} // default is to treat as decimal
final BigInteger value = new BigInteger(str.substring(pos), radix);
return negate ? value.negate() : value;
}
/**
* Convert a {@code String} to a {@code BigDecimal}.
*
* Returns {@code null} if the string is {@code null}.
*
* @param str a {@code String} to convert, may be null
* @return converted {@code BigDecimal} (or null if the input is null)
* @throws NumberFormatException if the value cannot be converted
*/
public static BigDecimal createBigDecimal(final String str) {
if (str == null) {
return null;
}
// handle JDK1.3.1 bug where "" throws IndexOutOfBoundsException
if (StringUtils.isBlank(str)) {
throw new NumberFormatException("A blank string is not a valid number");
}
return new BigDecimal(str);
}
/**
* Utility method for {@link #createNumber(java.lang.String)}.
*
* Returns {@code true} if s is {@code null}.
*
* @param str the String to check
* @return if it is all zeros or {@code null}
*/
private static boolean isAllZeros(final String str) {
if (str == null) {
return true;
}
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) != '0') {
return false;
}
}
return !str.isEmpty();
}
/**
* Checks whether the {@code String} contains only
* digit characters.
*
* {@code Null} and empty String will return
* {@code false}.
*
* @param str the {@code String} to check
* @return {@code true} if str contains only Unicode numeric
*/
public static boolean isDigits(final String str) {
return StringUtils.isNumeric(str);
}
/**
* Utility method for {@link #createNumber(java.lang.String)}.
*
* Returns mantissa of the given number.
*
* @param str the string representation of the number
* @return mantissa of the given number
*/
private static String getMantissa(final String str) {
return getMantissa(str, str.length());
}
/**
* Utility method for {@link #createNumber(java.lang.String)}.
*
* Returns mantissa of the given number.
*
* @param str the string representation of the number
* @param stopPos the position of the exponent or decimal point
* @return mantissa of the given number
*/
private static String getMantissa(final String str, final int stopPos) {
final char firstChar = str.charAt(0);
final boolean hasSign = firstChar == '-' || firstChar == '+';
return hasSign ? str.substring(1, stopPos) : str.substring(0, stopPos);
}
}