JSONObject getstring removes the zero from string - java

I'm trying to get numerical values that start with 0s from a JSONObject. The problem is the method converts the string into a double. Example:
JSONObject:
{
"LATITUDE1":41,
"LATITUDE2":06962
}
When I use
String lat2 = object.getString("LATITUDE2");
the String lat2 is displayed as 6962.0. How can I make it so that the string is displayed as it is in the json file (as 06962)?
I will then need to concatenate the two values and add a dot in between them to get a decimal number such as 41.06962 that's why I need to get the values as strings.
Thanks

If it's a string let it be a string:
{
"LATITUDE1":"41",
"LATITUDE2":"06962"
}

Related

NumberFormatingExcepton if App is launched First Time

I have 4 TextViews. 3 of them display results of EditText input value in another activity, and it's saved with shared preferences.
The fourth TextView needs to display sum of that previous 3 TextViews.
I get the error: NumberFormatingException invalid double ""
This is my code:
// GETTING VALUES FOR FIRST 3 TEXTVIEWS
textViewRezultat1RMPotisakSKlupe.setText(settings.getString("benchSave", null));
textViewRezultat1RMCucanj.setText(settings.getString("squatSave", null));
textViewRezultat1RMMrtvoDizanje.setText(settings.getString("deadSave", null));
//LITTLE BIT OF MATH TO GET VALUE OF FOURTH
double prvo = Double.parseDouble(textViewRezultat1RMPotisakSKlupe.getText().toString());
double drugo = Double.parseDouble(textViewRezultat1RMCucanj.getText().toString());
double trece = Double.parseDouble(textViewRezultat1RMMrtvoDizanje.getText().toString());
double rezultat = 0;
rezultat = (prvo + drugo + trece);
textViewRezultat1RMUkupno.setText(Double.toString(rezultat));
That works like a charm.
The problem is, I get the error I mentioned above if the app is launched for the first time (with no stored data).
Can anyone help me solve it?
Actually the problem occurs when trying to parse a double from a string that is not representing a number or just simply null.
parseDouble
public static double parseDouble(String s)
throws NumberFormatException
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Parameters:
s - the string to be parsed.
Returns: the double value represented by the
string argument.
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable
double.
So you need to test both scenarios to be sure you are not in either of the faulty cases.
String prvoString = textViewRezultat1RMPotisakSKlupe.getText().toString();
Double prvo;
if(prvoString != null) { //shouldn't occur
try {
prvo = Double.parseDouble(prvoString);
} catch (NumberFormatException ex) { //inputs like "" or "banana"
//Tell the user he is entering invalid input
}
}
So why is this occuring when your app is running for the first time? The code that is parseDouble is executed when your view is loaded and trying to parse empty ("") strings.
Before doing double prvo = Double.parseDouble() always check whether your Strings are valid or not because if your String is empty, that is like "", you can't convert this to Double as its not a number.
So before every Double.parseDouble check like this -
if (!TextUtils.isEmpty(yourString))
Double.parseDouble(yourString);

Multiplying ascii code and getting string back

I am trying to convert a string to ascii code and then multiplying that concatenation of the ascii codes by a number.
For example
String message = "Hello";
String result = "";
ArrayList arrayList = new ArrayList();
int temp;
for(int i = 0; i < message.length(); i++){
temp = (int) message.charAt(i);
result = result + String.value(temp).toString();
arrayList.add(String.valueOf(temp).toString());
}
I have tried two different ways, but there is always a catch with each one.
If I just concatenate all the ascii codes together into a string and I get 72101108108111 as my new string, the problem now is how can I get the original string back from this? This is because it is not obvious where each one character code starts and ends and the next one begins.
Another way I tried doing this was to use an array. I would receive |72|101|108|108|111| in an array. Obviously the codes are split here, but if I wanted to multiply this whole array (all the numbers as one number) by a number and then how would I get the array back together?
These are two different ways I have thought to solve this, but I have no idea how to get the string back out of these if I multiply the ascii by a number.
You don't need to modify the original string nor the ascii code string. Just have them both there, then whenever you need to get the numerical value of the string, just use X.valueOf(...)** method. Example,
final String message = "Hello";
final String result = "72101108108111";
long value = Long.valueOf(result);
If you do not want to store the two strings, then you should go with the array method. To get a numerical value, you simply concatenate all the strings in the array into one and use the X.valueOf(..) method.
And to get back the original string, use Integer.valueOf(...) on each string in the array, then cast each one to char.
System.out.println((char)Integer.valueOf("111").intValue());
** Note by X.valueOf(..), X doesn't have to be Long or Integer as I have shown. As you mentioned the value can get really large so BigInteger should be prefered above others

How to convert string to double

double d=0.0;
for (String k : word.keySet()) {
System.out.println(k + "\t" + word.get(k));
d+=Double.valueOf(word.get(k));
d+=word.get(k);
word.get(k);
}
System.out.println("Value\t"+d);
The values are in hashmap. Incompatible type error occurs in 5th line.how to correct it?
The line d+=Double.valueOf(word.get(k)); will correctly add the Double value of word.get(k) to your double d, provided the String is parsable as Double.
The line after it, however, adds a String to a double, which will not compile.
The last line in your loop doesn't make any sense, you are invoking get without actually using the value.
You can use Double.parseDouble()
Eg:
String str="2.25";
double d=Double.parseDouble(str);
System.out.println(d);
You can convert String value to Double like this--
double latitu=Double.parseDouble("21.2186653");
If the error is in 5th line that's because you are trying to add whatever you have in the set word with double d. Java do not know what you have in the set word so you can type cast it if the word is a set of double. Otherwise you have to parse the double from what "word.get(k)" returns.
try d+=(double) word.get(k), if word is a set of double
or d+=double.valueOf(word.get(k)). if you have string in the set word.
In your 5th line of sample code, you are trying to add a string value with a double. that's why you are getting error
use
d += Double.parseDouble(word.get(k));
rather than
d+=word.get(k)

How to convert a String number to two three decimal places in Java?

I am trying to convert a String number to two decimal places in Java. I saw lot of posts on satckoverflow but somehow I am getting an exception.
String number = "1.9040409535344458";
String result = String.format("%.2f", number);
System.out.println(result);
This is the exception I am getting -
java.util.IllegalFormatConversionException: f != java.lang.String
I would like to have 1.904 as the output. Does anyone know what wrong I am doing here?
You can try using a NumberFormat. For example:
String number = "1.9040409535344458";
NumberFormat formatter = new DecimalFormat("#0.000");
String result = formatter.format(Double.valueOf(number));
System.out.println(result);
Just declare number to be double :
Double number = 1.9040409535344458;
instead of
String number = "1.9040409535344458";
OUTPUT :
1.90
you should first convert the string into double and then change the decimal value
String number = "1.9040409535344458";
double result = Double.parseDouble(number);//converts the string into double
result = result *100;//adjust the decimal value
System.out.println(result);
You are using a format not meant for a String. I would recommend either converting your String to a double or storing it as a double in the first place. Convert the String to a double, and pass that double to String.format.

Remove decimals after a numeric value in java

Hi I have a excel file reading application which reads every cell in the file.
whenever a cell contains a numeric value the app is treating it a numeric cell.
For example the cell contains (40002547) the application will treat this as numeric cell. I cab get the value by using this code:
SONum = String.valueOf(cellSONum.getNumericCellValue());
Well that works fine. My Problem is it appends decimal at the end of the string. it will be (40002547.0). I need it to be as is. Thanks in advance
It's because cellSONum.getNumericCellValue() is returning a floating point type. If you force it to an integer before calling valueOf(), you should get the string representation in an integral form, if indeed that's what you want for all possibilities:
SONum = String.valueOf((int)cellSONum.getNumericCellValue());
You can see this in the following code:
class Test {
public static void main(String[]args) {
double d = 1234;
System.out.println(String.valueOf(d));
System.out.println(String.valueOf((int)d));
}
}
which outputs:
1234.0
1234
However, if you want to just get rid of .0 at the end of any string but allow non-integral values to survive, you can just remove the trailing text yourself:
class Test {
public static void main(String[]args) {
double d1 = 1234;
double d2 = 1234.567;
System.out.println(String.valueOf(d1).replaceFirst("\\.0+$", ""));
System.out.println(String.valueOf(d2).replaceFirst("\\.0+$", ""));
}
}
That snippet outputs:
1234
1234.567
Try with split().
SONum = String.valueOf(cellSONum.getNumericCellValue());
SONum = SONum.split("\\.")[0];
When you split 40002547.0 with . ,the split function returns two parts and the first one you need.
If you want to be sure you are not cutting of any valid decimals, you can use regexp also:
String pattern = "\.0+"; // dot followed by any number of zeros
System.out.println(String.valueOf(cellSONum.getNumericCellValue()).replaceAll(pattern, ""));
More on java regexp for example: http://www.vogella.com/articles/JavaRegularExpressions/article.html
As PaxDiablo also mentions, cellSONum.getNumericCellValue() returns a floating point.
You can cast this to Long or int to get rid of all behind the '.'
String SONum = String.valueOf(cellSONum.getNumericCellValue().longValue());
used as example:
String SONum = String.valueOf((new Double(0.5)).longValue());
SONum = ""+cellSONum.getNumericCellValue().split(".")[0];
try
double value = 23.0;
DecimalFormat df = new DecimalFormat("0.##");
System.out.println("bd value::"+ df.format(value))
Consider using BigDecimal.
You could simply say
BigDecimal scaledDecimal = new BigDecimal(value).setScale(0, RoundingMode.HALF_EVEN);
This will help in case your input is String and you need result also in String
1). Convert the string to Double using Double.parseDouble,
2). Type cast to int, then convert to string using String.valueOf()
private String formatText(String text) {
try {
return String.valueOf((int) Double.parseDouble(text));
} catch (NumberFormatException e) {
return text;
}
}
You can do Explicit type casting to remove the decimals,
double desvalue = 3.586;
int value = (int)desvalue;

Categories