Android的我怎么能转换为字符串倍增不失precision? [英] Android How can I convert String to Double without losing precision?
问题描述
我想开发一次计算基础应用,但得到的一个问题。
i want to develop one calculation base application but getting one problem.
试过如下
double add_num = 10.06
String data = edittext.getText().toString();
值分配给数据
// data = 1000.06
现在我将字符串转换为加倍
now i am converting string to double
double amount = Double.parseDouble(data);
// amount = 1000.0
double final_amount = amount + add_num;
// final_amount = 1010.0
越来越final_amount为 1000.0 这是不正确的,因为金额价值正在丧失precision我想正确的答案是的 1000.06
getting final_amount is 1000.0 which is not correct because amount value is losing precision i want the correct answer which is 1000.06
请让我知道正确的方法,而无需使用format()方法
please let me know correct way without using format() method
推荐答案
嗯,首先正确的值是 1010.12
,而不是 1000.06
。而这code:
Well, first of all correct value is 1010.12
, not 1000.06
. And this code:
double add_num = 10.06;
String value = "1000.06";
double amount = Double.parseDouble(value);
double final_amount = amount + add_num;
System.out.println(final_amount);
打印 1010.1199999999999
,这是正确的。
如果你只是想和所需的precision打印数量,使用中的一项:
If you just want to print the number with the desired precision, use one of:
// Prints with two decimal places: "1010.12"
System.out.format("%.2f", final_amount);
System.out.println(String.format("%.2f", final_amount));
// Example, set TextView text with two decimal places:
edittext.setText(String.format("%.2f", final_amount));
顺便说一句,在你的code你有:
By the way, in your code you have:
String data = edittext.getText().toString();
double amount = Double.parseDouble(value); // value?
应该不会有呢?
double amount = Double.parseDouble(data);
这篇关于Android的我怎么能转换为字符串倍增不失precision?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!