如何获得小数点后仅两位数的双精度值。
例如,如果a = 190253.80846153846 那么结果值应该是a = 190253.80
尝试: 我试过这个:
public static DecimalFormat twoDForm = new DecimalFormat("#0.00");
代码
a = Double.parseDouble(twoDForm.format(((a))));
但我得到的价值就像190253.81而不是我想要的190253.80
那么我应该为它改变什么呢?
答案 0 :(得分:6)
因为Math.round()返回与参数最接近的int。通过添加1/2将结果舍入为整数,取结果的最低值,并将结果转换为int类型。
使用Math.floor()
示例强>
public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) {
double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
Rval = Rval * p;
double tmp = Math.floor(Rval);
System.out.println("~~~~~~tmp~~~~~"+tmp);
return (double)tmp/p;
}
完整的源代码
class ZiggyTest2{
public static void main(String[] args) {
double num = 190253.80846153846;
double round = roundMyData(num,2);
System.out.println("Rounded data: " + round);
}
public static double roundMyData(double Rval, int numberOfDigitsAfterDecimal) {
double p = (float)Math.pow(10,numberOfDigitsAfterDecimal);
Rval = Rval * p;
double tmp = Math.floor(Rval);
System.out.println("~~~~~~tmp~~~~~"+tmp);
return (double)tmp/p;
}
}
答案 1 :(得分:5)
试试这个,
制作BigDecimal的对象
double a = 190253.80846153846;
BigDecimal bd = new BigDecimal(a);
BigDecimal res = bd.setScale(2, RoundingMode.DOWN);
System.out.println("" + res.toPlainString());
答案 2 :(得分:3)
没有图书馆:
a = (float) (((int)(a * 100)) / 100.0f);
或者,对于double:
a = (double) (((int)(a * 100)) / 100.0);
答案 3 :(得分:2)
答案 4 :(得分:2)
Following code works for me.
public static double round(double value, int places) {
//here 2 means 2 places after decimal
long factor = (long) Math.pow(10, 2);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
答案 5 :(得分:1)
double dValue = 10.12345;
try{
String str = Double.toString(dValue*100);`
str = str.split("[.]")[0];
dValue = Double.parseDouble(str)/100;
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(dValue);
使用此代码。您可以获得所需的输出。
答案 6 :(得分:1)
这是另一种写它的方式,类似于Shabbir的^但我认为更容易阅读。我其实想要围绕它;如果它显示.349,我想看到.35 - 但如果你不想那样,那么你可以使用Math.floor代替我的Math.round:
public static double round(double time){
time = Math.round(100*time);
return time /= 100;
}
这是我的完整代码:我正在开发一个程序,在给定的时间段内找到3个随机1分钟的时间间隔,用于我正在进行的研究项目。
import java.lang.*;
import java.util.*;
class time{
public static void main (String[] args){
int time = Integer.parseInt(args[0]);
System.out.println("time is: "+time);
//randomly select one eligible start time among many
//the time must not start at the end, a full min is needed from times given
time = time - 1;
double start1 = Math.random()*time;
System.out.println(start1);
start1 = round(start1);
System.out.println(start1);
}
public static double round(double time){
time = Math.round(100*time);
return time /= 100;
}
}
以当前输出运行它:
[bharthur@unix2 edu]$ java time 12
time is: 12
10.757832858914
10.76
[bharthur@unix2 edu]$ java time 12
time is: 12
0.043720864837211715
0.04