NumberUtils源码分析
生活随笔
收集整理的這篇文章主要介紹了
NumberUtils源码分析
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
NumberUtils類介紹
org.apache.commons.lang3.math.NumberUtils?類是org.apache.commons包下的一個(gè)工具類,主要功能入類名描述的一樣。數(shù)字工具類。?
運(yùn)行環(huán)境
- OS:Win7 64bit
- idea:IntelliJ IDEA 2017
- jdkVersion:1.7.0_79 64 bit
- 使用的pom.xml
- 1
- 2
- 3
- 4
- 5
NumberUtils 源碼解析
NumberUtils源碼如下:
package org.apache.commons.lang3.math;import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger;import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.Validate;/*** <p>Provides extra functionality for Java Number classes.</p>** @since 2.0*/ public class NumberUtils {/** 可重復(fù)使用的Long常量0L */public static final Long LONG_ZERO = Long.valueOf(0L);/** 可重復(fù)使用的Long常量1L */public static final Long LONG_ONE = Long.valueOf(1L);/** 可重復(fù)使用的Long常量-1L */public static final Long LONG_MINUS_ONE = Long.valueOf(-1L);/** 可重復(fù)使用的Integer常量0 */public static final Integer INTEGER_ZERO = Integer.valueOf(0);/** 可重復(fù)使用的Integer常量1 */public static final Integer INTEGER_ONE = Integer.valueOf(1);/** 可重復(fù)使用的Integer常量-1 */public static final Integer INTEGER_MINUS_ONE = Integer.valueOf(-1);/** 可重復(fù)使用的Short常量0 */public static final Short SHORT_ZERO = Short.valueOf((short) 0);/** 可重復(fù)使用的Short常量1 */public static final Short SHORT_ONE = Short.valueOf((short) 1);/** 可重復(fù)使用的Short常量-1 */public static final Short SHORT_MINUS_ONE = Short.valueOf((short) -1);/** 可重復(fù)使用的Byte常量0 */public static final Byte BYTE_ZERO = Byte.valueOf((byte) 0);/** 可重復(fù)使用的Byte常量1 */public static final Byte BYTE_ONE = Byte.valueOf((byte) 1);/** 可重復(fù)使用的Byte常量-1 */public static final Byte BYTE_MINUS_ONE = Byte.valueOf((byte) -1);/** 可重復(fù)使用的Double常量0.0d */public static final Double DOUBLE_ZERO = Double.valueOf(0.0d);/** 可重復(fù)使用的Double常量1.0d */public static final Double DOUBLE_ONE = Double.valueOf(1.0d);/** 可重復(fù)使用的Double常量-1.0d */public static final Double DOUBLE_MINUS_ONE = Double.valueOf(-1.0d);/** 可重復(fù)使用的Float常量0.0f */public static final Float FLOAT_ZERO = Float.valueOf(0.0f);/** 可重復(fù)使用的Float常量1.0f */public static final Float FLOAT_ONE = Float.valueOf(1.0f);/** 可重復(fù)使用的Float常量-1.0f */public static final Float FLOAT_MINUS_ONE = Float.valueOf(-1.0f);/*** 我們使用的時(shí)候無需創(chuàng)建該工具類,像這樣使用 NumberUtils.toInt("6");* 該構(gòu)造方法是為了符合JavaBean的規(guī)范*/public NumberUtils() {super();}//-----------------------------------------------------------------------/***轉(zhuǎn)換str為int,如果轉(zhuǎn)換失敗則返回0 **/public static int toInt(final String str) {return toInt(str, 0);}/***轉(zhuǎn)換str為int,如果轉(zhuǎn)換失敗則返回defaultValue**/public static int toInt(final String str, final int defaultValue) {if(str == null) {return defaultValue;}try {return Integer.parseInt(str);} catch (final NumberFormatException nfe) {return defaultValue;}}/***轉(zhuǎn)換str為long,如果轉(zhuǎn)換失敗則返回0L**/public static long toLong(final String str) {return toLong(str, 0L);}/***轉(zhuǎn)換str為long,如果轉(zhuǎn)換失敗則返回defaultValue**/public static long toLong(final String str, final long defaultValue) {if (str == null) {return defaultValue;}try {return Long.parseLong(str);} catch (final NumberFormatException nfe) {return defaultValue;}}/***轉(zhuǎn)換str為float,如果轉(zhuǎn)換失敗則返回0.0f**/public static float toFloat(final String str) {return toFloat(str, 0.0f);}/***轉(zhuǎn)換str為float,如果轉(zhuǎn)換失敗則返回defaultValue*/public static float toFloat(final String str, final float defaultValue) {if (str == null) {return defaultValue;}try {return Float.parseFloat(str);} catch (final NumberFormatException nfe) {return defaultValue;}}/***轉(zhuǎn)換str為double,如果轉(zhuǎn)換失敗則返回0.0d*/public static double toDouble(final String str) {return toDouble(str, 0.0d);}/***轉(zhuǎn)換str為double,如果轉(zhuǎn)換失敗則返回defaultValue*/public static double toDouble(final String str, final double defaultValue) {if (str == null) {return defaultValue;}try {return Double.parseDouble(str);} catch (final NumberFormatException nfe) {return defaultValue;}}/***轉(zhuǎn)換str為byte,如果轉(zhuǎn)換失敗則返回0*/public static byte toByte(final String str) {return toByte(str, (byte) 0);}/***轉(zhuǎn)換str為byte,如果轉(zhuǎn)換失敗則返回defaultValue*/public static byte toByte(final String str, final byte defaultValue) {if(str == null) {return defaultValue;}try {return Byte.parseByte(str);} catch (final NumberFormatException nfe) {return defaultValue;}}/***轉(zhuǎn)換str為short,如果轉(zhuǎn)換失敗則返回0*/public static short toShort(final String str) {return toShort(str, (short) 0);}/***轉(zhuǎn)換str為short,如果轉(zhuǎn)換失敗則返回defaultValue*/public static short toShort(final String str, final short defaultValue) {if(str == null) {return defaultValue;}try {return Short.parseShort(str);} catch (final NumberFormatException nfe) {return defaultValue;}}/*** 將一個(gè)String的值轉(zhuǎn)換為java.lang.Number* 如果這個(gè)字符串以0x、0X、-0x、-0X、#、-#開始,這個(gè)字符將轉(zhuǎn)換成 hexadecimal Integer類型,如果前綴后面的數(shù)字超過8個(gè)則轉(zhuǎn)換成Long類型* 如果超過16個(gè)則轉(zhuǎn)換成BIgInteger。* 還會檢查這個(gè)值是否是以預(yù)定義的字符結(jié)束,例如'f','F','d','D','l','L'.如果找到對應(yīng)的,將開始依次創(chuàng)建較大的類型直到找到能匹配這個(gè)值的類型。* 如果沒有找到類型標(biāo)識符,將作為小數(shù)進(jìn)行驗(yàn)證并且是依次從Intger到BigInteger,Float 到BigDecimal。* 0開頭的數(shù)字將作為八進(jìn)制轉(zhuǎn)換,返回的數(shù)字是相應(yīng)的Integer,Long 或BigDecimal * 如果參數(shù)為空則返回null* 這個(gè)方法不會對參數(shù)進(jìn)行trim操作,如果頭部或尾部有空格的話將會生成NumberFormatExceptions* */public static Number createNumber(final String str) throws NumberFormatException {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 herefinal 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) { // 是十六進(jìn)制 we have a hex numberchar firstSigDigit = 0; // 去掉開頭的0 strip leading zeroesfor(int i = pfxLen; i < str.length(); i++) {firstSigDigit = str.charAt(i);if (firstSigDigit == '0') { // 統(tǒng)計(jì)有多少個(gè)0開頭 count leading zeroespfxLen++;} else {break;}}final int hexDigits = str.length() - pfxLen; //計(jì)算不包含0的數(shù)字的長度if (hexDigits > 16 || hexDigits == 16 && firstSigDigit > '7') { // 使用BigIntegerreturn createBigInteger(str);}if (hexDigits > 8 || hexDigits == 8 && firstSigDigit > '7') { // 使用Longreturn createLong(str);}return createInteger(str);}final char lastChar = str.charAt(str.length() - 1); //獲取最后一個(gè)數(shù)字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 offsetif (decPos > -1) { // 這個(gè)是一個(gè)小數(shù)數(shù)字 there is a decimal pointif (expPos > -1) { // 這是一個(gè)指數(shù) there is an exponentif (expPos < decPos || expPos > str.length()) { // 防止雙指數(shù)導(dǎo)致IOOBE prevents double exponent causing IOOBEthrow 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()) { // 防止雙指數(shù)導(dǎo)致IOOBE prevents double exponent causing IOOBEthrow 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.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 = NumberUtils.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 wantreturn f;}} catch (final NumberFormatException nfe) { // NOPMD// ignore the bad number}//$FALL-THROUGH$case 'd' :case 'D' :try {final Double d = NumberUtils.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, Bigintegertry {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//也許是Float,Double,BigDecimalfinal 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);}/*** createNumber()方法使用* 獲取尾數(shù)的,也就是返回不包括符號位的數(shù)字*/private static String getMantissa(final String str) {return getMantissa(str, str.length());}/*** createNumber()方法使用* 獲取尾數(shù)的,也就是返回不包括符號位的數(shù)字可以指定獲取長度*/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);}/*** createNumber()方法使用* 如果字符串為空返回true,如果字符串中的沒有等于0的返回true*/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.length() > 0;}//-----------------------------------------------------------------------/*** 轉(zhuǎn)換String為Float* 如果String為空則返回null*/public static Float createFloat(final String str) {if (str == null) {return null;}return Float.valueOf(str);}/*** 轉(zhuǎn)換String為Double* 如果String為空則返回null*/public static Double createDouble(final String str) {if (str == null) {return null;}return Double.valueOf(str);}/*** 轉(zhuǎn)換String為Integer,處理hex和octal進(jìn)制。* 注意0開頭表示octal進(jìn)制,不會進(jìn)行trim操作*/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);}/*** 轉(zhuǎn)換String為Long,處理hex和octal進(jìn)制。* 注意0開頭表示octal進(jìn)制,不會進(jìn)行trim操作*/public static Long createLong(final String str) {if (str == null) {return null;}return Long.decode(str);}/*** 轉(zhuǎn)換String為BigInteger* 從3.2版本后可以處理hex(0x or #開頭)和octal (0開頭)進(jìn)制* 字符串為null返回null */public static BigInteger createBigInteger(final String str) {if (str == null) {return null;}int pos = 0; // offset within stringint 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)) { // hexradix = 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 digitsradix = 8;pos ++;} // default is to treat as decimalfinal BigInteger value = new BigInteger(str.substring(pos), radix);return negate ? value.negate() : value;}/*** 轉(zhuǎn)換String為Double* 如果String為空則返回null*/public static BigDecimal createBigDecimal(final String str) {if (str == null) {return null;}// handle JDK1.3.1 bug where "" throws IndexOutOfBoundsExceptionif (StringUtils.isBlank(str)) {throw new NumberFormatException("A blank string is not a valid number");}if (str.trim().startsWith("--")) {// this is protection for poorness in java.lang.BigDecimal.// it accepts this as a legal value, but it does not appear// to be in specification of class. OS X Java parses it to// a wrong value.throw new NumberFormatException(str + " is not a valid number.");}return new BigDecimal(str);}// Min in array//--------------------------------------------------------------------/*** 返回?cái)?shù)組的最小值*/public static long min(final long... array) {// Validates inputvalidateArray(array);// Finds and returns minlong min = array[0];for (int i = 1; i < array.length; i++) {if (array[i] < min) {min = array[i];}}return min;}/*** 返回?cái)?shù)組中最小的* 從3.4版本后 修改方法簽名 min(int[]) to min(int...)*/public static int min(final int... array) {// Validates inputvalidateArray(array);// Finds and returns minint min = array[0];for (int j = 1; j < array.length; j++) {if (array[j] < min) {min = array[j];}}return min;}/*** 返回?cái)?shù)組中最小的* 從3.4版本后 修改方法簽名 min(short[]) to min(short...)*/public static short min(final short... array) {// Validates inputvalidateArray(array);// Finds and returns minshort min = array[0];for (int i = 1; i < array.length; i++) {if (array[i] < min) {min = array[i];}}return min;}/*** 返回?cái)?shù)組中最小的* 從3.4版本后 修改方法簽名 min(byte[]) to min(byte...)*/public static byte min(final byte... array) {// Validates inputvalidateArray(array);// Finds and returns minbyte min = array[0];for (int i = 1; i < array.length; i++) {if (array[i] < min) {min = array[i];}}return min;}/*** 返回?cái)?shù)組中最小的* 從3.4版本后 修改方法簽名 min(double[]) to min(double...)*/public static double min(final double... array) {// Validates inputvalidateArray(array);// Finds and returns mindouble min = array[0];for (int i = 1; i < array.length; i++) {if (Double.isNaN(array[i])) {return Double.NaN;}if (array[i] < min) {min = array[i];}}return min;}/*** 返回?cái)?shù)組中最小的* 從3.4版本后 修改方法簽名 min(float[]) to min(float...)*/public static float min(final float... array) {// Validates inputvalidateArray(array);// Finds and returns minfloat min = array[0];for (int i = 1; i < array.length; i++) {if (Float.isNaN(array[i])) {return Float.NaN;}if (array[i] < min) {min = array[i];}}return min;}// Max in array//--------------------------------------------------------------------/*** 返回?cái)?shù)組中最大的* 從3.4版本后 修改方法簽名 min(long[]) to min(long...)*/public static long max(final long... array) {// Validates inputvalidateArray(array);// Finds and returns maxlong max = array[0];for (int j = 1; j < array.length; j++) {if (array[j] > max) {max = array[j];}}return max;}/*** 返回?cái)?shù)組中最大的* 從3.4版本后 修改方法簽名 min(int[]) to min(int...)*/public static int max(final int... array) {// Validates inputvalidateArray(array);// Finds and returns maxint max = array[0];for (int j = 1; j < array.length; j++) {if (array[j] > max) {max = array[j];}}return max;}/*** 返回?cái)?shù)組中最大的* 從3.4版本后 修改方法簽名 min(short[]) to min(short...)*/public static short max(final short... array) {// Validates inputvalidateArray(array);// Finds and returns maxshort max = array[0];for (int i = 1; i < array.length; i++) {if (array[i] > max) {max = array[i];}}return max;}/*** 返回?cái)?shù)組中最大的* 從3.4版本后 修改方法簽名 min(byte[]) to min(byte...)*/public static byte max(final byte... array) {// Validates inputvalidateArray(array);// Finds and returns maxbyte max = array[0];for (int i = 1; i < array.length; i++) {if (array[i] > max) {max = array[i];}}return max;}/*** 返回?cái)?shù)組中最大的* 從3.4版本后 修改方法簽名 min(double[]) to min(double...)*/public static double max(final double... array) {// Validates inputvalidateArray(array);// Finds and returns maxdouble max = array[0];for (int j = 1; j < array.length; j++) {if (Double.isNaN(array[j])) {return Double.NaN;}if (array[j] > max) {max = array[j];}}return max;}/*** 返回?cái)?shù)組中最大的* 從3.4版本后 修改方法簽名 min(float[]) to min(float...)*/public static float max(final float... array) {// Validates inputvalidateArray(array);// Finds and returns maxfloat max = array[0];for (int j = 1; j < array.length; j++) {if (Float.isNaN(array[j])) {return Float.NaN;}if (array[j] > max) {max = array[j];}}return max;}/*** 校驗(yàn)參數(shù)數(shù)組是不是nulll或empty*/private static void validateArray(final Object array) {Validate.isTrue(array != null, "The Array must not be null");Validate.isTrue(Array.getLength(array) != 0, "Array cannot be empty.");}// 3 param min//-----------------------------------------------------------------------/*** 獲取三個(gè)long類型參數(shù)中最小的*/public static long min(long a, final long b, final long c) {if (b < a) {a = b;}if (c < a) {a = c;}return a;}/*** 獲取三個(gè)int類型參數(shù)中最小的*/public static int min(int a, final int b, final int c) {if (b < a) {a = b;}if (c < a) {a = c;}return a;}/*** 獲取三個(gè)short類型參數(shù)中最小的*/public static short min(short a, final short b, final short c) {if (b < a) {a = b;}if (c < a) {a = c;}return a;}/*** 獲取三個(gè)byte類型參數(shù)中最小的*/public static byte min(byte a, final byte b, final byte c) {if (b < a) {a = b;}if (c < a) {a = c;}return a;}/*** 獲取三個(gè)double類型參數(shù)中最小的*/public static double min(final double a, final double b, final double c) {return Math.min(Math.min(a, b), c);}/*** 獲取三個(gè)float類型參數(shù)中最小的* 如果有一個(gè)值是NaN,則NaN將返回,當(dāng)做無盡處理*/public static float min(final float a, final float b, final float c) {return Math.min(Math.min(a, b), c);}// 3 param max//-----------------------------------------------------------------------/*** 獲取三個(gè)long類型參數(shù)中最大的*/public static long max(long a, final long b, final long c) {if (b > a) {a = b;}if (c > a) {a = c;}return a;}/*** 獲取三個(gè)int類型參數(shù)中最大的*/public static int max(int a, final int b, final int c) {if (b > a) {a = b;}if (c > a) {a = c;}return a;}/*** 獲取三個(gè)short類型參數(shù)中最大的*/public static short max(short a, final short b, final short c) {if (b > a) {a = b;}if (c > a) {a = c;}return a;}/*** 獲取三個(gè)byte類型參數(shù)中最大的*/public static byte max(byte a, final byte b, final byte c) {if (b > a) {a = b;}if (c > a) {a = c;}return a;}/*** 獲取三個(gè)double類型參數(shù)中最大的*/public static double max(final double a, final double b, final double c) {return Math.max(Math.max(a, b), c);}/*** 獲取三個(gè)float類型參數(shù)中最大的*/public static float max(final float a, final float b, final float c) {return Math.max(Math.max(a, b), c);}//-----------------------------------------------------------------------/*** 判斷字符串僅僅包含數(shù)字字符* null或empty返回false*/public static boolean isDigits(final String str) {return StringUtils.isNumeric(str);}/*** 過時(shí)的方法被isCreatable取代*/@Deprecatedpublic static boolean isNumber(final String str) {return isCreatable(str);}/*** 校驗(yàn)String是否是一個(gè)有效的Java number* 校驗(yàn)number包含hexadecimal 的標(biāo)記 0x or 0X、八進(jìn)制數(shù)字、科學(xué)計(jì)數(shù)法和其他的數(shù)字標(biāo)記類型,比如1234L* 以0開頭的非十六進(jìn)制的數(shù)統(tǒng)一作為八進(jìn)制的數(shù)處理。所以String為09將返回false,因?yàn)?不是一個(gè)有效的八進(jìn)制。但是是以0.開頭的數(shù)字,都作為十進(jìn)制處理* null或empty或blank字符串返回false*/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 frontfinal int start = chars[0] == '-' || chars[0] == '+' ? 1 : 0;final boolean hasLeadingPlusSign = start == 1 && chars[0] == '+';if (sz > start + 1 && chars[start] == '0') { // leading 0if (chars[start + 1] == 'x' || chars[start + 1] == 'X') { // leading 0x/0Xint 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 octalint 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 qualifiersint 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 exponentreturn false;}hasDecPoint = true;} else if (chars[i] == 'e' || chars[i] == 'E') {// we've already taken care of hex.if (hasExp) {// two E'sreturn 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') {if (SystemUtils.IS_JAVA_1_6 && hasLeadingPlusSign && !hasDecPoint) {return false;}// no type qualifier, OKreturn true;}if (chars[i] == 'e' || chars[i] == 'E') {// can't have an E at the last bytereturn false;}if (chars[i] == '.') {if (hasDecPoint || hasExp) {// two decimal points or dec in exponentreturn false;}// single trailing decimal point after non-exponent is okreturn 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 pointreturn foundDigit && !hasExp && !hasDecPoint;}// last character is illegalreturn false;}// allowSigns is true iff the val ends in 'E'// found digit it to make sure weird stuff like '.' and '1E-' doesn't passreturn !allowSigns && foundDigit;}/*** 校驗(yàn)提供的字符串是否可以解析為number* 可解析的number包括下面方法可以執(zhí)行字符串 Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String). * 這個(gè)方法可以替代java.text.ParseException異常* 十六進(jìn)制和科學(xué)計(jì)數(shù)符號認(rèn)為是不可解析的* @since 3.4*/public static boolean isParsable(final String str) {if (StringUtils.isEmpty(str)) {return false;}if (str.charAt(str.length() - 1) == '.') {return false;}if (str.charAt(0) == '-') {if (str.length() == 1) {return false;}return withDecimalsParsing(str, 1);}return withDecimalsParsing(str, 0);}private static boolean withDecimalsParsing(final String str, final int beginIdx) {int decimalPoints = 0;for (int i = beginIdx; i < str.length(); i++) {final boolean isDecimalPoint = str.charAt(i) == '.';if (isDecimalPoint) {decimalPoints++;}if (decimalPoints > 1) {return false;}if (!isDecimalPoint && !Character.isDigit(str.charAt(i))) {return false;}}return true;}/****比例兩個(gè)int的大小,在Java7有提供相同的方法* @since 3.4*/public static int compare(final int x, final int y) {if (x == y) {return 0;}return x < y ? -1 : 1;}/*** 比例兩個(gè)long的大小,在Java7有提供相同的方法* @since 3.4*/public static int compare(final long x, final long y) {if (x == y) {return 0;}return x < y ? -1 : 1;}/*** 比例兩個(gè)long的大小,在Java7有提供相同的方法* @since 3.4*/public static int compare(final short x, final short y) {if (x == y) {return 0;}return x < y ? -1 : 1;}/*** 比例兩個(gè)byte的大小,在Java7有提供相同的方法*/public static int compare(final byte x, final byte y) {return x - y;} }- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
- 309
- 310
- 311
- 312
- 313
- 314
- 315
- 316
- 317
- 318
- 319
- 320
- 321
- 322
- 323
- 324
- 325
- 326
- 327
- 328
- 329
- 330
- 331
- 332
- 333
- 334
- 335
- 336
- 337
- 338
- 339
- 340
- 341
- 342
- 343
- 344
- 345
- 346
- 347
- 348
- 349
- 350
- 351
- 352
- 353
- 354
- 355
- 356
- 357
- 358
- 359
- 360
- 361
- 362
- 363
- 364
- 365
- 366
- 367
- 368
- 369
- 370
- 371
- 372
- 373
- 374
- 375
- 376
- 377
- 378
- 379
- 380
- 381
- 382
- 383
- 384
- 385
- 386
- 387
- 388
- 389
- 390
- 391
- 392
- 393
- 394
- 395
- 396
- 397
- 398
- 399
- 400
- 401
- 402
- 403
- 404
- 405
- 406
- 407
- 408
- 409
- 410
- 411
- 412
- 413
- 414
- 415
- 416
- 417
- 418
- 419
- 420
- 421
- 422
- 423
- 424
- 425
- 426
- 427
- 428
- 429
- 430
- 431
- 432
- 433
- 434
- 435
- 436
- 437
- 438
- 439
- 440
- 441
- 442
- 443
- 444
- 445
- 446
- 447
- 448
- 449
- 450
- 451
- 452
- 453
- 454
- 455
- 456
- 457
- 458
- 459
- 460
- 461
- 462
- 463
- 464
- 465
- 466
- 467
- 468
- 469
- 470
- 471
- 472
- 473
- 474
- 475
- 476
- 477
- 478
- 479
- 480
- 481
- 482
- 483
- 484
- 485
- 486
- 487
- 488
- 489
- 490
- 491
- 492
- 493
- 494
- 495
- 496
- 497
- 498
- 499
- 500
- 501
- 502
- 503
- 504
- 505
- 506
- 507
- 508
- 509
- 510
- 511
- 512
- 513
- 514
- 515
- 516
- 517
- 518
- 519
- 520
- 521
- 522
- 523
- 524
- 525
- 526
- 527
- 528
- 529
- 530
- 531
- 532
- 533
- 534
- 535
- 536
- 537
- 538
- 539
- 540
- 541
- 542
- 543
- 544
- 545
- 546
- 547
- 548
- 549
- 550
- 551
- 552
- 553
- 554
- 555
- 556
- 557
- 558
- 559
- 560
- 561
- 562
- 563
- 564
- 565
- 566
- 567
- 568
- 569
- 570
- 571
- 572
- 573
- 574
- 575
- 576
- 577
- 578
- 579
- 580
- 581
- 582
- 583
- 584
- 585
- 586
- 587
- 588
- 589
- 590
- 591
- 592
- 593
- 594
- 595
- 596
- 597
- 598
- 599
- 600
- 601
- 602
- 603
- 604
- 605
- 606
- 607
- 608
- 609
- 610
- 611
- 612
- 613
- 614
- 615
- 616
- 617
- 618
- 619
- 620
- 621
- 622
- 623
- 624
- 625
- 626
- 627
- 628
- 629
- 630
- 631
- 632
- 633
- 634
- 635
- 636
- 637
- 638
- 639
- 640
- 641
- 642
- 643
- 644
- 645
- 646
- 647
- 648
- 649
- 650
- 651
- 652
- 653
- 654
- 655
- 656
- 657
- 658
- 659
- 660
- 661
- 662
- 663
- 664
- 665
- 666
- 667
- 668
- 669
- 670
- 671
- 672
- 673
- 674
- 675
- 676
- 677
- 678
- 679
- 680
- 681
- 682
- 683
- 684
- 685
- 686
- 687
- 688
- 689
- 690
- 691
- 692
- 693
- 694
- 695
- 696
- 697
- 698
- 699
- 700
- 701
- 702
- 703
- 704
- 705
- 706
- 707
- 708
- 709
- 710
- 711
- 712
- 713
- 714
- 715
- 716
- 717
- 718
- 719
- 720
- 721
- 722
- 723
- 724
- 725
- 726
- 727
- 728
- 729
- 730
- 731
- 732
- 733
- 734
- 735
- 736
- 737
- 738
- 739
- 740
- 741
- 742
- 743
- 744
- 745
- 746
- 747
- 748
- 749
- 750
- 751
- 752
- 753
- 754
- 755
- 756
- 757
- 758
- 759
- 760
- 761
- 762
- 763
- 764
- 765
- 766
- 767
- 768
- 769
- 770
- 771
- 772
- 773
- 774
- 775
- 776
- 777
- 778
- 779
- 780
- 781
- 782
- 783
- 784
- 785
- 786
- 787
- 788
- 789
- 790
- 791
- 792
- 793
- 794
- 795
- 796
- 797
- 798
- 799
- 800
- 801
- 802
- 803
- 804
- 805
- 806
- 807
- 808
- 809
- 810
- 811
- 812
- 813
- 814
- 815
- 816
- 817
- 818
- 819
- 820
- 821
- 822
- 823
- 824
- 825
- 826
- 827
- 828
- 829
- 830
- 831
- 832
- 833
- 834
- 835
- 836
- 837
- 838
- 839
- 840
- 841
- 842
- 843
- 844
- 845
- 846
- 847
- 848
- 849
- 850
- 851
- 852
- 853
- 854
- 855
- 856
- 857
- 858
- 859
- 860
- 861
- 862
- 863
- 864
- 865
- 866
- 867
- 868
- 869
- 870
- 871
- 872
- 873
- 874
- 875
- 876
- 877
- 878
- 879
- 880
- 881
- 882
- 883
- 884
- 885
- 886
- 887
- 888
- 889
- 890
- 891
- 892
- 893
- 894
- 895
- 896
- 897
- 898
- 899
- 900
- 901
- 902
- 903
- 904
- 905
- 906
- 907
- 908
- 909
- 910
- 911
- 912
- 913
- 914
- 915
- 916
- 917
- 918
- 919
- 920
- 921
- 922
- 923
- 924
- 925
- 926
- 927
- 928
- 929
- 930
- 931
- 932
- 933
- 934
- 935
- 936
- 937
- 938
- 939
- 940
- 941
- 942
- 943
- 944
- 945
- 946
- 947
- 948
- 949
- 950
- 951
- 952
- 953
- 954
- 955
- 956
- 957
- 958
- 959
- 960
- 961
- 962
- 963
- 964
- 965
- 966
- 967
- 968
- 969
- 970
- 971
- 972
- 973
- 974
- 975
- 976
- 977
- 978
- 979
- 980
- 981
- 982
- 983
- 984
- 985
- 986
- 987
- 988
- 989
- 990
- 991
- 992
- 993
- 994
- 995
- 996
- 997
- 998
- 999
- 1000
- 1001
- 1002
- 1003
- 1004
- 1005
- 1006
- 1007
- 1008
- 1009
- 1010
- 1011
- 1012
- 1013
- 1014
- 1015
- 1016
- 1017
- 1018
- 1019
- 1020
- 1021
- 1022
- 1023
- 1024
- 1025
- 1026
- 1027
- 1028
- 1029
- 1030
- 1031
- 1032
- 1033
- 1034
- 1035
- 1036
- 1037
- 1038
- 1039
- 1040
- 1041
- 1042
- 1043
- 1044
- 1045
- 1046
- 1047
- 1048
- 1049
- 1050
- 1051
- 1052
- 1053
- 1054
- 1055
- 1056
- 1057
- 1058
- 1059
- 1060
- 1061
- 1062
- 1063
- 1064
- 1065
- 1066
- 1067
- 1068
- 1069
- 1070
- 1071
- 1072
- 1073
- 1074
- 1075
- 1076
- 1077
- 1078
- 1079
- 1080
- 1081
- 1082
- 1083
- 1084
- 1085
- 1086
- 1087
- 1088
- 1089
- 1090
- 1091
- 1092
- 1093
- 1094
- 1095
- 1096
- 1097
- 1098
- 1099
- 1100
- 1101
- 1102
- 1103
- 1104
- 1105
- 1106
- 1107
- 1108
- 1109
- 1110
- 1111
- 1112
- 1113
- 1114
- 1115
- 1116
- 1117
- 1118
- 1119
- 1120
- 1121
- 1122
常用方法
- 比較方法
- 1
- 校驗(yàn)數(shù)字的
- 1
- 2
- 是否可以解析
- 1
- 創(chuàng)建Java類型
- 1
- 2
- 將字符串轉(zhuǎn)換成數(shù)字類型,轉(zhuǎn)換失敗賦值默認(rèn)值
- 1
- 這個(gè)方法很厲害的,支持十六進(jìn)制,八進(jìn)制,科學(xué)計(jì)數(shù)法,和L,f的
from:?https://blog.csdn.net/facekbook/article/details/77338293
總結(jié)
以上是生活随笔為你收集整理的NumberUtils源码分析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JVM调优总结(6):新一代的垃圾回收算
- 下一篇: NumberUtils用法