java.lang.NumberFormatException: Invalid double - android

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

Related

Need to round off two points after decimal digit

I'm working on an app and facing an issue. I've tried a number of solutions but nothing solved my problem.
I need to round off two digits after decimal point.
For Example.
9.225 should be rounded off to 9.23
Thank you.
For Kotlin use "%.2f".format(number), for Java use String.format("%.2f", number)
Result:
You can use String.format("%.2f", d), this will rounded automatically. d is your value.
OR
You can use this
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
Log.d(df.format(d));
You can get as a float value as well like below.
float value = Float.valueOf(df.format(d)); // Output will be 1.24
I would have gone with a probable over the top solution however this is what i came up with.
It uses regex to split the string value of the number passed and then rounds up/down depending on the leading digit after the decimal place. It will return a Double in the instance but you can change that if you like. It does throw IllegalArgumentException, but thats taste dependant.
/**
* #param value the value that is being transformed
* #param decimalPlace the decimal place you want to return to
* #return transformed value to the decimal place
* #throws IllegalArgumentException
*/
Double roundNumber(#NonNull Double value, #NonNull Integer decimalPlace) throws IllegalArgumentException {
String valueString = value.toString();
if(valueString.length()> decimalPlace+1){
throw new IllegalArgumentException(String.format("The string value of %s is not long enough to have %dplaces", valueString, decimalPlace));
}
Pattern pattern = Pattern.compile("(\\d)('.')(\\d)");
Matcher matcher = pattern.matcher(valueString);
if (matcher.groupCount() != 4) { //0 = entire pattern, so 4 should be the total ?
throw new IllegalArgumentException(String.format("The string value of %s does not contain three groups.", valueString));
}
String decimal = matcher.group(3);
int place = decimal.charAt(decimalPlace);
int afterDecimalPlace = decimal.charAt(decimalPlace + 1);
String newDecimal = decimal.substring(0, decimalPlace - 1);
newDecimal += afterDecimalPlace > 5 ? (place + 1) : place;
return Double.parseDouble(matcher.group(1) + "." + newDecimal);
}

Prevent numbers from changing according to the locale in android

When the user change the locale in device the numbers are also getting changed according to the selected locale. This is causing NumberFormatException while performing mathematical operations and app is getting crashed. The code snippet which is causing the crash is given below.
public static double ToDataUnitMB(double _dataBytes){
double dDataBytes;
dDataBytes = Double.parseDouble(getDecimalFormat().format(_dataBytes / 1048576));
return dDataBytes; }
This code snippet is causing NumberFormatException and the value in _dataBytes is shown as "७२.४१". Can anyone help me to prevent the number from changing when user change the locale.
Update
I am getting the value "७२.४१" after performing the below operation getDecimalFormat().format(_dataBytes / 1048576)
So while parsing to Double it is showing numberFormatException
Since you're starting with raw _dataBytes you have several options how to format number independent of the locale.
First Approach:
You can modify following snippet to your needs. It will give you the same output regardless of the user locale.
String patern = "###.##"; //your pattern as per need
Locale locale = new Locale("en", "US");
DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getNumberInstance(locale);
decimalFormat.applyPattern(patern);
double formatedDouble = Double.parseDouble(decimalFormat.format(_dataBytes/(1024*1024f)));
Keep in mind that this method also makes grouping and decimal separators to be fixed, so that comma and dot will alway be used as, respectively, grouping separator and decimal separator.
Second Approach:
If you do not strictly require Double you could generate formatted String with something similar to following method:
String generateFormatedFileSize(long _dataBytes) {
String formatedFileSize = "";
long bytes = _dataBytes;
short unit = 1024;
if (bytes < unit)
formatedFileSize = bytes + " B";
else {
int exp = (int) (Math.log(bytes) / Math.log(unit));
formatedFileSize = String.format("%.1f %sB", bytes / Math.pow(unit, exp), "KMGT".charAt(exp - 1));
}
return formatedFileSize;
}
This formatting will be sensitive to grouping separator and decimal separator, but otherwise insensitive to Locale.
For Local that uses "US" numbering format, this will give you following output:
12.5 KB
5.3 B
8.0 MB
And for Local using "European" numbering format:
12,5 KB
5,3 B
8,0 MB
Off course, these two methods are not exclusive and you could use some mix of these approaches at different parts of the App.

Is language conditional in some operations?

I'm developing an app where I use the Geocoder to get a place's coordinates.
The operative is this:
The user defines an address.
The geocoder finds that address and I get the coordinates from that address.
This coordinates are in decimal format and I need them in degrees-minutos so I format them.
To format the coordinates from decimal to degrees-minutes I use:
String frmtLatitude = Location.convert(Double.parseDouble(lat), Location.FORMAT_MINUTES);
So, if I have for example this latitude 43.249591 in decimal value, it returns it like this 43:14.97546.
After this, I have to make some operations to finally get the latitude with this appearance: 4314.975
When I do this operations, one of them is to split the value using the ".". I split 14.97546 to get in one hand the 14 and in the other 97546.
Until here, everything ok. It works fine when I have my phone's language selected to be in english. But if I select to be in spanish, the app crashes. I have followed the stacktrace and it points there. Is like that in english when using the first commented function to convert from decimal to degrees-minutes it separates the decimals with a "." but if I have it in spanish, it separates them with a ",".
Can this really happen or the cause could be another thing?
We can look at the source code of the convert method
public static String convert(double coordinate, int outputType) {
if (coordinate < -180.0 || coordinate > 180.0 ||
Double.isNaN(coordinate)) {
throw new IllegalArgumentException("coordinate=" + coordinate);
}
if ((outputType != FORMAT_DEGREES) &&
(outputType != FORMAT_MINUTES) &&
(outputType != FORMAT_SECONDS)) {
throw new IllegalArgumentException("outputType=" + outputType);
}
StringBuilder sb = new StringBuilder();
// Handle negative values
if (coordinate < 0) {
sb.append('-');
coordinate = -coordinate;
}
DecimalFormat df = new DecimalFormat("###.#####");
if (outputType == FORMAT_MINUTES || outputType == FORMAT_SECONDS) {
int degrees = (int) Math.floor(coordinate);
sb.append(degrees);
sb.append(':');
coordinate -= degrees;
coordinate *= 60.0;
if (outputType == FORMAT_SECONDS) {
int minutes = (int) Math.floor(coordinate);
sb.append(minutes);
sb.append(':');
coordinate -= minutes;
coordinate *= 60.0;
}
}
sb.append(df.format(coordinate));
return sb.toString();
}
We can see that it uses a DecimalFormat with a given pattern. So, if we look to the DecimalFormat constructor :
public DecimalFormat(String pattern) {
// Always applyPattern after the symbols are set
this.symbols = new DecimalFormatSymbols(Locale.getDefault());
applyPattern(pattern, false);
}
We can see here that even if we give a pattern, it uses the locale values. The javadoc also said :
Parameters:
pattern A non-localized pattern string.
To finish, we can go here to see the different local variant of numbers representation : http://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html
So we can see that US-English use the "dot format" and that Spanish use "comma format".
To answer your question : the proflem you're facing is probably due to the Decimal format of your locale. I advice you to be REALLY CAREFUL when converting types of objects to make manipulation on them. Converting an int to a String should be only to display it.
I think you should seperate decimal part of your number when it stills a float (or any decimal type) and then convert your object to a String to display it. You can take a look at Math class or search SO to get some example on how to this ;)
Also, as #Dmitry said, you can get DecimalSeparator with DecimalFormatSymbols.getDecimalSeparator().
Sources
Location.convert(double,int) source code
DecimalFormat(String) source code
Java "Decimal and thousands separators"
You are right, decimal seperator depends on your locale. You can get it by something like this
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols formatSymbols = df.getDecimalFormatSymbols();
char separator = formatSymbols.getDecimalSeparator();

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.

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

Categories

Resources