Android:如何在十进制值之后得到两位数? 不想截断该值
如何得到小数点后只有两位数的双精度值。
例如,如果a = 190253.80846153846,那么结果值应该类似于a = 190253.80
试试:我试过这个:
public static DecimalFormat twoDForm = new DecimalFormat("#0.00");
在代码中
a = Double.parseDouble(twoDForm.format(((a))));
但我得到的价值像190253.81,而不是我想190253.80
那么我应该为它改变什么呢?
因为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; } }
尝试这个,
制作BigDecimal的对象
double a = 190253.80846153846; BigDecimal bd = new BigDecimal(a); BigDecimal res = bd.setScale(2, RoundingMode.DOWN); System.out.println("" + res.toPlainString());
没有图书馆:
a = (float) (((int)(a * 100)) / 100.0f);
或者,对于double:
a = (double) (((int)(a * 100)) / 100.0);
我认为这将是价值的一部分,检查一下
(float)Math.round(value * 100) / 100
从此链接回合十进制数
或者这个例子
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; }
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);
使用此代码。 您可以获得所需的输出。
这是另一种写它的方式,类似于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