I'm working on an app and facing an issue. I've tried a number of solutions but nothing solved my problem. I need to round off two digits after decimal point.
For Example.
9.225 should be rounded off to 9.23
Thank you.
I'm working on an app and facing an issue. I've tried a number of solutions but nothing solved my problem. I need to round off two digits after decimal point.
For Example.
9.225 should be rounded off to 9.23
Thank you.
You can use String.format("%.2f", d)
, this will rounded automatically. d
is your value.
OR
You can use this
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
Log.d(df.format(d));
You can get as a float value as well like below.
float value = Float.valueOf(df.format(d)); // Output will be 1.24
I would have gone with a probable over the top solution however this is what i came up with.
It uses regex to split the string value of the number passed and then rounds up/down depending on the leading digit after the decimal place. It will return a Double in the instance but you can change that if you like. It does throw IllegalArgumentException
, but thats taste dependant.
/**
* @param value the value that is being transformed
* @param decimalPlace the decimal place you want to return to
* @return transformed value to the decimal place
* @throws IllegalArgumentException
*/
Double roundNumber(@NonNull Double value, @NonNull Integer decimalPlace) throws IllegalArgumentException {
String valueString = value.toString();
if(valueString.length()> decimalPlace+1){
throw new IllegalArgumentException(String.format("The string value of %s is not long enough to have %dplaces", valueString, decimalPlace));
}
Pattern pattern = Pattern.compile("(\\d)('.')(\\d)");
Matcher matcher = pattern.matcher(valueString);
if (matcher.groupCount() != 4) { //0 = entire pattern, so 4 should be the total ?
throw new IllegalArgumentException(String.format("The string value of %s does not contain three groups.", valueString));
}
String decimal = matcher.group(3);
int place = decimal.charAt(decimalPlace);
int afterDecimalPlace = decimal.charAt(decimalPlace + 1);
String newDecimal = decimal.substring(0, decimalPlace - 1);
newDecimal += afterDecimalPlace > 5 ? (place + 1) : place;
return Double.parseDouble(matcher.group(1) + "." + newDecimal);
}