Android How can I convert String to Double without losing precision? [duplicate] - android

This question already has answers here:
How can I convert String to Double without losing precision in Java?
(4 answers)
Closed 9 years ago.
i want to develop one calculation base application but getting one problem.
Tried as below
double add_num = 10.06
String data = edittext.getText().toString();
value assign to data is
// 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
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
please let me know correct way without using format() method

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);
prints 1010.1199999999999, which is correct.
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));
By the way, in your code you have:
String data = edittext.getText().toString();
double amount = Double.parseDouble(value); // value?
Shouldn't it be?
double amount = Double.parseDouble(data);

String s="1000.06";
double d=Double.parseDouble(s);
System.out.println(d);
The above code give output: 1000.06

You should use String.ValueOf(double d);
For Example:-
Double to String
String value=String.valueOf(1000.06);
OR
String value=String.valueOf(add_num);
String to Double
Double value=Double.valueOf("1000.06");
OR
Double value=Double.valueOf(add_num);

Related

Converting TextView value to double variable

In front I set the text like that with the priceFormat being S$%.2f.
textPrice.setText(String.format(priceFormat, item.getPrice()));
Now I want to convert it to a double variable which I definitely think I have to make use of the priceFormat but I have no idea how to. This bottom line is wrong.
double Price=Double.parseDouble(textPrice.getText());
You need to convert the textPrice.getText() to a String since its Double.parseDouble(String):
double price = Double.parseDouble(mStatus.getText().toString());
You also have to eliminate the S$ and the trailing .:
double price = Double.parseDouble(mStatus.getText().toString().replaceAll("S\\$|\\.$", ""));
Of course you should make this less error-prone:
double price = 0d;
try {
price = Double.parseDouble(mStatus.getText().toString().replaceAll("S\\$|\\.$", ""));
}
catch (NumberFormatException e) {
// show an error message to the user
textPrice.setError("Please enter a valid number");
}
you need to remove that S$ before parsing, one of the way is:
String text = textPrice.getText();
String priceText = text.split("$")[1].trim(); //splitting numeric characters with the currency characters
double priceVal = Double.parseDouble(priceText); //parsing it to double

Getting invalid double, but the error shows a proper one

My application does some basic arithmetic processes and then adds them to a TextView. Because I want them the result be shown up to XX,XX I format my string with %.2f. Now, when I try to retrieve this result and use it in another arithmetic process, it gives me an error of:
java.lang.NumberFormatException: Invalid double: "8,86" (or any number for that matter)
How can I make the second process convert the string from the TextViewwithout getting an error?
process 1
int newProductQuantity = Integer.valueOf(productQuantity.getText().toString());
double newProductPrice = Double.valueOf(productPrice.getText().toString());
double newProductVAT = Double.valueOf(productVat.getText().toString());
double newProductPriceSum = ((newProductPrice + (newProductPrice * (newProductVAT / 100))) * newProductQuantity);
String newProductPriceSumTexta = String.format("%.2f", newProductPriceSum);
productPriceSum.setText(newProductPriceSumTexta);
process 2
double newOrderFinalLastSum = Double.parseDouble(newOrderFinalSum.getText().toString());
double newOrderFinalNewSum = Double.parseDouble(productPriceSum.getText().toString());
double newOrderFinalOmegaSum = newOrderFinalLastSum + newOrderFinalNewSum; //error is here
String newOrderFinalOmegaSumText = String.format("%.2f", newOrderFinalOmegaSum);
newOrderFinalSum.setText(newOrderFinalOmegaSumText);
your issue is Locale related. If you want always a dot . as separator, you should specify a Locale that use it. You can use format method that takes as first parameter a Locale object. For instance
String.format(Locale.UK,...
From the documentation of public static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string,
and arguments.
where
l - The locale to apply during formatting. If l is null then no
localization is applied.

change format of double like ***.***,**

I have double amount. Let amount to be 500000.12. I want to set value of the amount to TextView like this format 500,000.12 (where 12 is cents , 500,000 is dollars).
I wrote this function and it works
private String getAmountAsString(double amount) {
double integralPart = amount % 1;
int fractionalPart = (int) (amount - integralPart);
int integral = (int) integralPart * 100;
String strFractional = String.format("%,d", fractionalPart);
String strAmount = (strFractional + "." + String.valueOf(integral));
return strAmount;
}
But I think that there can be some easy and good way of doing this with java native functions. Can anybody help to find functions or some better way?
various Locale can be used to format float, double etc. You can use:
String.format(Locale.<Your Locale>, "%1$,.2f", myDouble);
Here .2f represents how many digits you want after decimal. If you are not specifying any locale it will use the default locale.
In String class this method is overloaded as:
format(String format, Object... args)
&
format(Locale l, String format, Object... args)
For more info have a look: Link1 , Link2 and Link3
Therefore NumberFormats are used. They are good to handle local differents for different countries.
//define a local, gets automated if a point or comma is correct in this Country.
NumberFormat anotherFormat = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
anotherDFormat.applyPattern("#.00");//set the number of digits afer the point
anotherDFormat.setGroupingUsed(true);// set grouping
anotherDFormat.setGroupingSize(3);//and size of grouping
double myDouble = 123456.78;
String numberWithSeparators = anotherDFormat.format(myDouble);//convert it
I think you have to take a look at this one
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

remove latitude and longitude fraction part after 6 digit

i get lat and long in this format
Latitude23.132679999999997, Longitude72.20081833333333
but i want to in this format
Latitude = 23.132680 and Longitude 72.200818
how can i convert
double Latitude = 23.132679999999997;
int precision = Math.pow(10, 6);
double new_Latitude = double((int)(precision * Latitude))/precision;
This will give you only 6 digits after decimal point.
double d=23.132679999999997;
DecimalFormat dFormat = new DecimalFormat("#.######");
d= Double.valueOf(dFormat .format(d));
Once I solved my problem like this -
String.format("%.6f", latitude);
Return value is string. So you can use this if you need string result.
If you need double you can convert using Double.parseDouble() method.
So you want round a double to an arbitrary number of digits, don't you?
can use like
DecimalFormat df = new DecimalFormat("#,###,##0.00");
System.out.println(df.format(364565.14343));
If you have Latitude and Longitude as String then you can do
latitude = latitude.substring(0,latitude.indexOf(".")+6);
Of course you should check that there are at least 6 characters after "." by checking string length

Convert String to Double excluding part of the string

How to convert double to a string value that I get from the spinner, for example: "10 (ton)."
In summary:
How to convert string to double and delete the part (ton)?
I need only the value 10
Another option is using Java's substring method in the String class.
The signature is:
substring(int beginIndex, int endIndex)
Where endIndex equals to the index of the last character you want to include + 1.
In the case of your example, it will look like this:
String myString = "10 (ton)";
Double dbl = Double.parseDouble(myString.substring(0, 2));
Here is the link to the method:
Java substring
You must parse this String. Here is some example. Also use search.
Check these methods Double.parseDouble() and Double.toString() use these functions for converting double to string or vice-versa.
first you have to get rid of "(ton)" which can be achieved by using a String method for example
String inputString = "10 (ton)";
String str = inputString.split(" ")[0];
After that just parse the double Value
Double dbl = Double.parseDouble(str);
BTW: Not sure whether you want to go from double to string or vice-versa
i have a similar problem.
for correct formatting EditText text content to double value i use this code:
try {
String eAm = etAmount.getText().toString();
DecimalFormat dF = new DecimalFormat("0.00");
Number num = dF.parse(eAm);
mPayContext.amount = num.doubleValue();
} catch (Exception e) {
mPayContext.amount = 0.0d;
}
this is independet from current phone locale and return correct double value.
hope it's help;

Categories

Resources