java - 如何在android中对结果进行四舍五入而不失去精度

标签 java rounding precision bigdecimal

我正在 android 中构建一个基本的计算器功能。 但是当结果显示在 TextView 中时,我在对数字进行四舍五入时遇到了一些问题。

我正在做 123456789 * 123456789 的乘法并得到我无法容纳在我的 TextView 中的结果。 另外,在 Android 内置计算器中执行时,上述操作的实际结果是 1.5241E16。 谁能告诉我如何在我的计算器应用程序中获得这个结果? 下面是关于我正在尝试做的事情的小片段:

public static double round(double unrounded, int precision, int roundingMode)
    {
        BigDecimal bd = new BigDecimal(unrounded);
        BigDecimal rounded = bd.setScale(precision, roundingMode);
        return rounded.doubleValue();
    }

    num = num * Double.parseDouble(txtCalc.getText().toString());
    num = round(num, 3, BigDecimal.ROUND_HALF_UP); //where 3 is the precision of number

请帮助我实现 1...9 * 1....9 的结果 1.5241E16

最佳答案

科学计数法确实失去了准确性。 1.5241E16 只是意味着答案大约是 1.5241*10,000,000,000,000,000,这意味着如果您可以决定要显示多少位小数,您只需将数字除以 10^X 并将结果连接起来即可。

因此,如果我的结果数字是 1234567890,并且我想将其显示为小数点后 3 位。我会做 1234567890/10^9 (因为第一位数字后有 9 位数字),然后我会简单地连接 char 5 之后的所有内容(1 位表示整数,1 位表示点,然后 3 位小数)。如果要四舍五入最后一位小数,只需检查位置 6 处的数字是否大于或等于 5,然后将最后一位数字增加 1。

这里给出了您想要的结果。

double num1 = 123456789L;
double num2 = 123456789L;
String result = num1*num2+"";
if(result.contains("E")){ //if result is in scientific notation
    //take the first 6 characters only and part containing the E, drop everything else.
    result = result.substring(0, 6) + result.substring(result.indexOf("E"));
}
System.out.println("Result is = " + result);

我的 Groovy shell 的输出:

Result is = 1.5241E16

关于java - 如何在android中对结果进行四舍五入而不失去精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7021819/

相关文章:

javascript - AJAX 调用不同的应用程序上下文 (Java + Tomcat)

java - 如果属性没有规则,Hibernate 的 validateValue() 会抛出非法参数异常?

mysql - 如何正确地将纬度和经度坐标插入 mySQL float?

java - 如何避免 Java 中 double 造成的精度损失?

java - SLF4J 和记录器工厂

java - 尝试运行 Maven 项目时出现错误

sql - 为什么在oracle中剩余(25,10)为5时剩余(35,10)为-5?

C - 舍入问题 (CS50)

php - 在 PHP 中向 float 添加整数会将 float 四舍五入到小数点后一位

c - printf 和 scanf 如何处理浮点精度格式?