我正在开发一款应用,但遇到了一个问题。我尝试了许多解决方案,但没有解决我的问题。 我需要在小数点后四舍五入两位数。
例如。
9.225 应四舍五入为 9.23
谢谢。
答案 0 :(得分:1)
您可以使用 String.format("%.2f", d)
,它会自动四舍五入。 d
是您的价值。
或
你可以使用这个
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
Log.d(df.format(d));
您也可以像下面一样获取浮点值。
float value = Float.valueOf(df.format(d)); // Output will be 1.24
答案 1 :(得分:1)
答案 2 :(得分:0)
我会选择一个可能的顶级解决方案,但这就是我想出的。
它使用正则表达式分割传递的数字的字符串值,然后根据小数位后的前导数字向上/向下舍入。它将在实例中返回一个 Double 值,但您可以根据需要更改它。它确实抛出 IllegalArgumentException
,但这取决于口味。
/**
* @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);
}