[英]How do I round a double to two decimal places in Java?
这就是我将双精度数转换为2位小数的方法:
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
DecimalFormat twoDForm = new DecimalFormat("#.##");
return Double.valueOf(twoDForm.format(d));
}
如果金额= 25.3569或类似的东西,这很好用,但如果金额= 25.00或金额= 25.0,那么我得到25.0! 我想要的是舍入和格式化为2位小数。
只需使用:(简单如馅饼)
double number = 651.5176515121351;
number = Math.round(number * 100);
number = number/100;
输出为651.52
使用数字占位符( 0
),与' #
'尾随/前导零显示为不存在:
DecimalFormat twoDForm = new DecimalFormat("#.00");
你在用钱吗? 创建一个String
然后将其转换回来是非常循环的。
使用BigDecimal
。 这已经被广泛讨论过了。 你应该有一个Money
类,金额应该是BigDecimal
。
即使您没有使用资金,也请考虑BigDecimal
。
您不能 '将一个双精度值舍入到任意数量的小数位数',因为双精度数没有小数位。 您可以将double转换为带有N个小数位的base-10 String,因为base-10确实有小数位,但是当你将它转换回来时,你又回到了double-land,带有二进制小数位。
这是我能做到的最简单的事情,但它比我见过的大多数例子更容易完成工作。
double total = 1.4563;
total = Math.round(total * 100);
System.out.println(total / 100);
结果是1.46。
用这个
String.format(“%。2f”,doubleValue)//根据您的要求更改2。
您可以使用来自apache common的org.apache.commons.math.util.MathUtils
double round = MathUtils.round(double1, 2, BigDecimal.ROUND_HALF_DOWN);
您可以使用Apache Commons Math:
Precision.round(double x, int scale)
来源: http : //commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/Precision.html#round(double,%20int)
双倍金额= 25.00;
NumberFormat formatter = new DecimalFormat(“#0.00”);
的System.out.println(formatter.format(量));
你可以尝试这个:
public static String getRoundedValue(Double value, String format) {
DecimalFormat df;
if(format == null)
df = new DecimalFormat("#.00");
else
df = new DecimalFormat(format);
return df.format(value);
}
要么
public static double roundDoubleValue(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
DecimalFormat df = new DecimalFormat("###.##");
double total = Double.valueOf(val);
您的Money类可以表示为Long的子类,或者具有将货币值表示为本机long的成员。 然后,在为货币实例化分配值时,您将始终存储实际为真钱货币值的值。 您只需使用适当的格式输出Money对象(通过Money的重写toString()方法)。 例如,Money对象的内部表示中的$ 1.25是125.您将货币表示为美分,便士或任何您正在密封的货币中的最小面额是......然后在输出上格式化它。 不,你永远不能存储'非法'货币价值,比如1.257美元。
Math.round
是一个答案,
public class Util {
public static Double formatDouble(Double valueToFormat) {
long rounded = Math.round(valueToFormat*100);
return rounded/100.0;
}
}
void "test double format"(){
given:
Double performance = 0.6666666666666666
when:
Double formattedPerformance = Util.formatDouble(performance)
println "######################## formatted ######################### => ${formattedPerformance}"
then:
0.67 == formattedPerformance
}
假设金额可以是正数也可以是负数,舍入到小数点后两位可以使用下面的代码片段。
amount = roundTwoDecimals(amount);
public double roundTwoDecimals(double d) {
if (d < 0)
d -= 0.005;
else if (d > 0)
d += 0.005;
return (double)((long)(d * 100.0))/100);
}
从Java 1.8开始,您可以使用lambda表达式执行更多操作并检查null。 另外,下面的一个可以处理Float或Double和可变数量的小数点(包括2 :-))。
public static Double round(Number src, int decimalPlaces) {
return Optional.ofNullable(src)
.map(Number::doubleValue)
.map(BigDecimal::new)
.map(dbl -> dbl.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP))
.map(BigDecimal::doubleValue)
.orElse(null);
}
其中num是双精度数
在这里,我们采取2小数位
System.out.printf( “%2F”,NUM);
这是一种简单的方法,可以保证将myFixedNumber输出四舍五入到两位小数:
import java.text.DecimalFormat;
public class TwoDecimalPlaces {
static double myFixedNumber = 98765.4321;
public static void main(String[] args) {
System.out.println(new DecimalFormat("0.00").format(myFixedNumber));
}
}
其结果是: 98765.43
首先声明DecimalFormat
类的对象。 注意DecimalFormat
的参数是#.00
,这意味着四舍五入的正好是2位小数。
private static DecimalFormat df2 = new DecimalFormat("#.00");
现在,将格式应用于您的double值:
double input = 32.123456;
System.out.println("double : " + df2.format(input)); // Output: 32.12
注意在double input = 32.1;
情况下double input = 32.1;
然后输出将是32.10
,依此类推。
int i = 180;
int j = 1;
double div= ((double)(j*100)/i);
DecimalFormat df = new DecimalFormat("#.00"); // simple way to format till any deciaml points
System.out.println(div);
System.out.println(df.format(div));
如果您希望结果为两位小数,则可以执行此操作
// assuming you want to round to Infinity.
double tip = (long) (amount * percent + 0.5) / 100.0;
此结果不准确,但Double.toString(double)将为此更正并打印一到两个小数位。 但是,只要执行另一次计算,就可以得到一个不会隐式舍入的结果。 ;)
您可以使用此功能。
import org.apache.commons.lang.StringUtils;
public static double roundToDecimals(double number, int c)
{
String rightPad = StringUtils.rightPad("1", c+1, "0");
int decimalPoint = Integer.parseInt(rightPad);
number = Math.round(number * decimalPoint);
return number/decimalPoint;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.