Android:如何在十进制值之后得到两位数?不想截断该值 [英] Android : How to get just two digit after the point in decimal value ? dont want to trunc the value

查看:125
本文介绍了Android:如何在十进制值之后得到两位数?不想截断该值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得小数点后仅两位数的双精度值。

How to get the double value that is only two digit after decimal point.

例如,如果a = 190253.80846153846
则结果值应为喜欢a = 190253.80

For example if the a = 190253.80846153846 then the result value should be like a = 190253.80

尝试:
我试过这个:

Try: I have try with this:

public static DecimalFormat twoDForm = new DecimalFormat("#0.00");

代码

a = Double.parseDouble(twoDForm.format(((a))));

但是我的价值比190253.81而不是我想要190253.80

But i got the value like 190253.81 instead of that i want 190253.80

那么我应该为它改变什么呢?

So what should i have to change for it ??

推荐答案

因为Math.round()返回与参数最接近的int。通过添加1/2将结果舍入为整数,取结果的最低值,并将结果转换为int类型。
使用 Math.floor()

Because Math.round() Returns the closest int to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type int. Use 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;
              }
            }

这篇关于Android:如何在十进制值之后得到两位数?不想截断该值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆