Android的 - 避免STING到双转换指数 [英] Android - avoid exponential in STING to DOUBLE conversion

查看:188
本文介绍了Android的 - 避免STING到双转换指数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从价值的EditText和字符串存储。然后将其转换为加倍。虽然转换到7个字符正常工作,但如果我尝试添加超过7结果是1.23456789E8。这里是我的code

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

如何能得到正确的值,而不会丢失precision?

How can i get correct value without losing precision?

推荐答案

我解决它。我使用BigDecimal的,而不是双现在我的code是

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的 - 避免STING到双转换指数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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