String servicePrice = serviceListArrayList.get(position).getPrice();
System.out.println ("Price======>"+servicePrice);
price = Integer.parseInt(servicePrice);
System.out.println("IntPrice====>"+price);
I want to convert this servicePrice value to integer value but unfortunately got NumberFormatException,please help me from this error.
You will get a NumberFormatException if servicePrice is not a string representation of an integer (e.g. "1" or "123"). Examples include an empty string (""), text ("abc"), decimal numbers ("1.23"), currencies ("$1.23" or "$2"), or things that aren't valid numbers ("1.2.3" or "0..1")
If you aren't in control of the string, you'll want to use appropriate checks to handle if a bad value is entered
int val = 0;
try {
val = Integer.parseInt(str);
}
catch(NumberFormatException np) {
// handle the case - e.g. error Toast message
}
The exception NumberFormatException is just only because the servicePrice value is not the number String. ( Any string value which is not convertible to as number value)
Better you catch the, price = Integer.parseInt(servicePrice);
For example
try
{
price = Integer.parseInt(servicePrice);
}
catch(NumberFormatException ex)
{ // you can assign default as 0 here too.
price =0;
}
int price = Integer.parseInt(serviceprice)
Log what value is stored in serviceprice
You can only convert numbers to String not alphabets.
Your serviceListArrayList.get(position).getPrice() might be returning some price with alphabets such as rs or dollars.
So print serviceprice and check.
Related
I have this little crazy method that removes decimal places from string value.
private double getDoubleFromString(final String value) throws ParseException {
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number = format.parse(value);
return number.doubleValue();
}
It produces values with out comma ( , ) if local language is 'en' it working fine, in other languages that contains , in that strings it's returns value without comma.
Ex :
xx,x
result is xxx.
74,5 --> 745 (problem facing in this format)
74.5 --> 74.5 (working fine it string has dot)
I do need the separator to be a dot or a point and a comma along with value string. Does anybody have a clue of how to accomplish this little feat?
Try this
private double getDoubleFromString(final String value) throws ParseException {
String newvalue= value.replace(",",".");
NumberFormat format = NumberFormat.getInstance(Locale.getDefault());
Number number = format.parse(newvalue);
return number.doubleValue();
}
SAMPLE CODE
try {
Log.e("RESULT_DATA",getDoubleFromString("88,5")+"");
Log.e("RESULT_DATA",getDoubleFromString("79.5")+"");
} catch (ParseException e) {
e.printStackTrace();
}
OUTPUT
03-22 18:37:09.173 7103-7103/? E/RESULT_DATA: 88.5
03-22 18:37:09.174 7103-7103/? E/RESULT_DATA: 79.5
i from API I receive next string:
String userId = "4463570100035744";
I need to convert it to int, so I tried next code:
try {
int id = Integer.parseInt(userId);
} catch (NumberFormatException e){
e.printStackTrace();
}
but I still catch exeption....
what can be the reason?
REASON: value is outside the range of an int
ACTION: You must use Long and not Integer .Use a long/Long instead.
Integer.MAX_VALUE = 2147483647
Integer.MIN_VALUE = -2147483648
Long.MAX_VALUE = 9223372036854775807
Long.MIN_VALUE = -9223372036854775808
4463570100035744 is too large a number for an Int32 variable. You could consider using a long variable type.
you take variable userId as String and you put integer value in it and then you parse it to convert in integer. Your mistake is you put integer value in String variable userId.
You need to put it like this :
String userId = "4463570100035744";
One more thing keep the size of variable in mind. I think value is too large then the size of int.
And now you edited your question, after people post answers to your actual problem.
You can refer to the docs for the Java primitive types to select the appropriate type for your variable: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
The primitive types available to store a number like your userId are:
byte (1 byte) Range: −128 to 127
short (2 bytes) Range: −32768 to 32767
int (4 bytes) Range: −2,147,483,648 to 2,147,483,647
float (4 bytes) Range: 3.4e−038 to 3.4e+038
long (8 bytes) Range: 9,223,372,036,854,775,808 to 9,223,372,036,854,755,807
double (8 bytes) Range: 1.7e−308 to 1.7e+038
Notice how your int is 4463570100035744 which compared to int has a difference of 4,463,567,952,552,097.
Your id variable would be best suited for a long.
try
{
long id = Long.parseLong(userId);
System.out.println("long id = " + id);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
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
I'm having an issue when I get a whole number from an EditText and try to change that to a decimal so I can use it for calculations. Could someone explain how to do this?
For Example. if someone was to enter 120 into the EditText and I got the integer from it, how would I then change that integer of 120 into 1.20 and continue calculations with it?
Thanks!!
EditText myEditText = (EditText)findViewById(R.id.YOUR_EDIT_TEXT_ID);
String numberAsString = myEditText.getText().toString();
double myDecimal;
try {
myDecimal = Double.parseDouble(numberAsString);
if (myDecimal >= 10)
{
int digits = 1 + (int)Math.floor(Math.log10(myDecimal));
myDecimal = myDecimal / ((Math.pow((double)10, ((double)digits) - 1)));
System.out.println(myDecimal);
}
} catch (NumberFormatException e) {
//handle exeption
e.printStackTrace();
}
You need to get the contents from your EditText as a string, and from there you can parse it into an integer. This is done like so:
int wholeNum = Integer.parseInt(yourEditText.getText().toString());
int three = Integer.parse("3");
I know you can use this to parse a string into an integer, there is probably a parse method in double aswell!
Check this also :
Convert a String to Double - Java
+1 to anthony for answering 1 minute before me haha
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;