remove latitude and longitude fraction part after 6 digit - android

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

Related

java.lang.NumberFormatException: Invalid double

I have a method to calculate Difference between two Latitude:
public static double distanceKM(LatLng latLng1, LatLng latLng2) {
int EARTH_RADIUS_KM = 6371;
double lat1Rad = Math.toRadians(latLng1.latitude);
double lat2Rad = Math.toRadians(latLng2.latitude);
double deltaLonRad = Math.toRadians(latLng2.longitude - latLng1.longitude);
double dist_travelled = Math
.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad)
* Math.cos(lat2Rad) * Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
dist_travelled = Double.parseDouble(new DecimalFormat("##.######")
.format(dist_travelled));
return dist_travelled;
}
Sometimes, this method throw Exception (I say sometimes, when I test in defference device):
java.lang.NumberFormatException: Invalid double: "0,179927"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
Can someone help me in this case? Thanks
The value of the double depends on the language of the device. For example, for devices in french the number 0.179927 becomes 0,179927 which will always throw a NumberFormatException when parsing it to double because of the comma.
You need to change the separator from a comma to a point.
You can change the separator either by setting a locale or using the DecimalFormatSymbols.
If you want the grouping separator to be a point, you can use a european locale:
NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;
Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);

Fatal Exception: java.lang.NumberFormatException

I get this exception from time to time, when I get a new location coordinate from the GPS, and I want to format it.
This is my code:
DecimalFormat decimalFormat = new DecimalFormat("0.00000");
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude())));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude())));
Why does this happen? The latitude and longitude that I get back from the location are both Doubles. I format it transforming it into the needed format (5 decimals after point) and then when I try to make a double back, it crashes. Why does this happen? And why not everytime, just sometimes?
Example on what crashed:
Fatal Exception: java.lang.NumberFormatException
Invalid double: "52,36959"
This is where I use it:
Log.i("","enteredd latitude is:" + location.getLatitude());
try{
DecimalFormat decimalFormat = new DecimalFormat("0.00000");
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", ".")));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude()).replace(",", ".")));
}catch (Exception e){
Log.e("","enteredd error deimal formating" + e.getMessage());
}
Log.i("","enteredd latitude is:" + location.getLatitude());
And the same thing for:
location = LocationServices.FusedLocationApi.getLastLocation(PSLocationCenter.getInstance().mLocationClient);
Question: Will it fix it if I do it like this?
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", ".")));
You are putting a double value into a decimal format, then parsing it back to double and using the very same value that you have gotten from the variable location to set the values for location. There is an exceeding amount of poor logic in this.
location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude())));
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude())));
location.getLatitude is the latitude, you do not need to set it.
You need to set a decimal separator:
DecimalFormat decimalFormat = new DecimalFormat("0.00000");
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
decimalFormat.setDecimalFormatSymbols(dfs);
From here: (android) decimalformat, uses comma in place of fullstop while formatting with "#.##"
Also:
Get location.
double latitude = location.getLatitude();
double longitude = location.getLongitude();
For the purposes of your app, you do not need to change this.
Just pass the values to the server that you need:
String lat = decimalFormat(latitude);
String long = decimalFormat(longitude);

Android location change Latitude and Longitude from DMS format to double

I have this format for a location (24°13'30.92"N,55°45'51.94"E) and I need to convert it through android to a double value like (24.225275, 55.764417).
I tried something like this and it did not work
String lonStr="24°13'30.92"N";
Double lon=Location.convert(lonStr);
Use substring and indexOf
extract minutes and second divide by 60 and 3600 respectively and
finally add degree part.
String str="24°13'30.92\"N,55°45'51.94\"E";
String s[]=str.split(",");
double lat=Integer.parseInt(s[0].substring(0,s[0].indexOf("°")))+(double)Integer.parseInt(s[0].substring(s[0].indexOf("°")+1, s[0].indexOf("'")))/60+ Double.parseDouble(s[0].substring(s[0].indexOf("'")+1, s[0].indexOf("\"")))/3600;
// same for longitude
System.out.println(String.format("%.6f", lat));
output:
24.225256

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

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);

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