[英]How can I prevent decimals being rounded when using DecimalFormat?
Can anyone help how can i prevent rounding decimal value.任何人都可以帮助我如何防止舍入十进制值。
DecimalFormat df = new DecimalFormat();
Object[] arrayRowResult = (Object[]) rowResult;
String a=df.format(arrayRowResult[0]) // [0] contain decimal(2,10) but format results rounded value
String b=df.format(arrayRowResult[1]) // [1] contain decimal(2,14) but format results rounded value
How can i prevent round off.我怎样才能防止四舍五入。
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(0);
df.setMaximumFractionDigits(2);
// .... your code
This will still round the numbers having more than two fraction digits -- change that value as you need it.这仍然会舍入具有两个以上小数位的数字——根据需要更改该值。
你试过跟随吗?
DecimalFormat df = new DecimalFormat("#.##");
package com.mkyong.test;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class TestDouble {
private static DecimalFormat df2 = new DecimalFormat(".##");
public static void main(String[] args) {
double input = 32.123456;
System.out.println("double : " + input);
System.out.println("double (default) : " + df2.format(input));
df2.setRoundingMode(RoundingMode.UP);
System.out.println("double (UP) : " + df2.format(input));
df2.setRoundingMode(RoundingMode.DOWN);
System.out.println("double (DOWN) : " + df2.format(input));
}
}
Copy Output复制输出
double : 32.123456
double (default) : 32.12
double (UP) : 32.13
double (DOWN) : 32.12
You need to add df.setRoundingMode(RoundingMode.DOWN);您需要添加df.setRoundingMode(RoundingMode.DOWN);
double a = 980.199999;
DecimalFormat df = new DecimalFormat("#,##0.00");
df.setRoundingMode(RoundingMode.DOWN);
String as = df.format(a);
System.out.println(as);
This is will even add 2 decimal point for integers if you don't need you can change DecimalFormat如果您不需要,这甚至会为整数添加 2 个小数点,您可以更改 DecimalFormat
Output: 980.19输出:980.19
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int ) http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int )
and和
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#setMinimumFractionDigits(int ) http://download.oracle.com/javase/1.4.2/docs/api/java/text/DecimalFormat.html#setMinimumFractionDigits(int )
Of course, both methods need that the precision is known a priori (it is not useful if it can have an arbitrary number of decimals).当然,这两种方法都需要先验知道精度(如果它可以有任意数量的小数,那就没用了)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.