微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何修复android中的“大计算错误”?

如何解决如何修复android中的“大计算错误”?

我正在开发一个计算器应用程序,它运行良好,但如果输出大于 15 位数字,则开始给出错误的计算。 以下是示例代码

private double result = 0;
edittext1 = (EditText) findViewById(R.id.edittext1);
edittext2 = (EditText) findViewById(R.id.edittext2);
button1 = (Button) findViewById(R.id.button1)
textview1 = (TextView) findViewById(R.id.textview1);
ArrayList<String> nums = new ArrayList<>();
ArrayList<String> signs = new ArrayList<>();

button1.setonClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View _view) {
        //This part is essential (adding strings to arraylists)
        nums.add(edittext1.getText().toString());
        nums.add(edittext2.getText().toString());
        signs.add("*");
        if (signs.contains("*")) {
            result = Double.parseDouble(nums.get((int)(0))) * Double.parseDouble(nums.get((int)(1)));
            //error here (perhaps)
            textview1.setText(new DecimalFormat(#.##).format(result));
        }
    }
});

现在,如果我将“9999999999999999”放入edittext1,将“1”放入edittext2,则textview1(结果TextView)显示“10000000000000000”。 数字越大,差异就越大。

如何解决这个问题?

这是我的第一个问题之一,如果它没有任何意义或者是一个愚蠢的问题,那么抱歉!

解决方法

我们使用 BigDecimal 进行高精度算术。我们还将它用于需要控制规模和四舍五入行为的 calculations

        double number1 = 0.05;
        double number2 = 0.06;
        double result = b - a;
result  = 0.009999999999999998

        BigDecimal number1 = new BigDecimal("0.05");
        BigDecimal number2 = new BigDecimal("0.06");
        BigDecimal result  = number2.subtract(number1);
result  = 0.01

你可以使用this

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。