Android-避免将字符串以指数形式转换为双精度 [英] Android - avoid exponential in string to double conversion

查看:203
本文介绍了Android-避免将字符串以指数形式转换为双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从edittext获取值并存储为字符串。然后它将转换为双精度。虽然最多转换7个字符正常运行,但如果我尝试添加7个以上的结果,则为1.23456789E8。这是我的代码

I trying to get value from edittext and stored as string. Then it converts to double. While converting up to 7 characters functioning normally but if i try to add more than 7 result is 1.23456789E8. Here is my code

String value = txtData.txtSearch.getText().toString();
// value = "987654321.45"

double amount1 = Double.parseDouble(value);
// amount1 = 9.8765432145E8

double amount2 = 0.05;

double result = (amount1 * amount2) / 100;
// result = 4.3827160725E14

计算后我得到4.3827160725E14这是不正确的答案是493827.16

after calculation i got 4.3827160725E14 which is not correct correct answer is 493827.16

如何在不损失精度的情况下获得正确的值?

How can i get correct value without losing precision?

推荐答案

我解决了。我使用BigDecimal而不是double,现在我的代码是

I solved it. i use BigDecimal instead of double now my code is

String value = txtData.txtSearch.getText().toString();
// value = "987654321.45"

BigDecimal amount1 = new BigDecimal(value);
// amount1 = "987654321.45"

BigDecimal amount2 = new BigDecimal(0.05);

BigDecimal result = (amount1.multiply(amount2)).divide(new BigDecimal(100));
result = result.setScale(2, RoundingMode.FLOOR);
// result = 493827.16

这篇关于Android-避免将字符串以指数形式转换为双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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