NumberUtils
- 03 Nov 2020
- 1 Minute to read
- Contributors
- Print
- DarkLight
NumberUtils
- Updated on 03 Nov 2020
- 1 Minute to read
- Contributors
- Print
- DarkLight
Article summary
Did you find this summary helpful?
Thank you for your feedback!
This helper/util class holds a number of small functions to handle common checks and transformations of numeric values.
Project
com.corzia.comflow.utils
List of methods:
isStringInteger
Used when you want to see if a string is an integer or not, so that you can safely perform a transformation. The argument is parsed to an Integer and the success/failure is handled with a catch statement.
Argument | String numericString |
Returns | True if the argument can be converted to Integer |
Example of usage
public static void callExample() {
if (NumbeUtils.isStringInteger("123") {
Integer myNumber = Integer.valueOf("123");
}
}
Code
public static boolean isStringInteger(String numericString) {
try {
Integer dummy = Integer.valueOf(numericString);
} catch (NumberFormatException e) {
return false;
}
return true;
}
isStringNumeric
The argument is parsed to an Double and the success/failure is handled with a catch statement.
Argument | String numericString |
Returns | True if the argument can be converted to a Double |
Example of usage
public static void callExample() {
if (NumberUtils.isStringNumeric("123.45")) {
BigDecimal myNumber = new BigDecimal("123.45");
}
}
Code
public static boolean isStringNumeric(String numericString) {
try {
Double.parseDouble(numericString);
return true;
} catch (NumberFormatException e) {
return false;
}
}
clearTrailingZerosFromNumericText
The method will remove any trailing zeros in a numeric text. If the text ends with a decimal separator it will be removed.
Examples:
- 123.1000 => 123.1
- 123,1000 => 123,1
- 1,200,300.000 => 1,200,300
Argument | String numericString |
Returns | New String without trailing zeros (and, possibly, decimal separator) |
Example of usage
String myCleanedNumericText = NumberUtils.clearTrailingZerosFromNumericText("123,400.50000");
Code
public static String clearTrailingZerosFromNumericText(String numericString) {
if (StringUtil.isBlankOrNullOr0(numericString)) return numericString;
String cleanedNumericText = numericString.trim();
if (!StringUtil.isBlankOrNull(cleanedNumericText) && cleanedNumericText.length() > 1 && cleanedNumericText.matches("^(\\d*[.,]\\d*)+$")) {
while (cleanedNumericText.substring(cleanedNumericText.length()-1, cleanedNumericText.length()).equals("0")) {
cleanedNumericText = cleanedNumericText.substring(0, cleanedNumericText.length()-1);
}
}
if (cleanedNumericText.substring(cleanedNumericText.length()-1).matches("[.,]")) {
cleanedNumericText = cleanedNumericText.substring(0, cleanedNumericText.length()-1);
}
return cleanedNumericText;
}
Was this article helpful?