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
Related
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.
I've noticed a strange bug while looking at my app on an Android device running 5.0.
On pre 5.0 devices my app will add commas into numbers where necessary. e.g "1,234" or "100,000"
On 5.0 devices the same code displays these numbers as "1234" or "100000". Has any one else noticed this?
I have included my code to format the numbers below - I'm not to sure what needs to change for lollipop devices to show the correct format.
public static String formatNumber(Integer number, String prefix) {
if (prefix == null) {
prefix = Constants.PREFIX_SYMBOL;
}
StringBuilder stringBuilder = new StringBuilder(prefix);
NumberFormat numberFormatter = NumberFormat.getIntegerInstance(new Locale("en_UK"));
stringBuilder.append("").append(numberFormatter.format(number));
return stringBuilder.toString();
}
So I think the solution to this is as follows
public static String formatNumber(Integer number, String prefix) {
if (prefix == null) {
prefix = Constants.PREFIX_SYMBOL;
}
StringBuilder stringBuilder = new StringBuilder(prefix);
NumberFormat numberFormatter = NumberFormat.getIntegerInstance();
stringBuilder.append("").append(numberFormatter.format(number));
return stringBuilder.toString();
}
Removing the Locale from the NumberFormat.getIntegerInstance(); call seems to do the trick. This is added in as some Locales will use non-ASCII decimal digits when formatting integers as specified here. I do not think that this is the case for the regions that my app is available in so it should do the trick.
EDIT:
NumberFormat numberFormatter = NumberFormat.getIntegerInstance(new Locale("en_UK"));
can be replaced with
NumberFormat numberFormatter = NumberFormat.getIntegerInstance(new Locale("en", "GB"));
This will prevent the default locales from using non-ASCII decimal digits.
To group digits you could use DecimalFormat instead of NumberFormat:
DecimalFormat formatter = new DecimalFormat("###,###");
will do the trick.
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
Firstly, I know Doubles aren't the best for currency, but in this case, precision is not profoundly important. So, I have a live app in the Play store and I found a problem with Euro currencies. For some reason, if a Euro localization is used (can't reproduce this with ADB localizations) users can enter a comma in a numberDecimal EditText to delimit the dollars and cents. So, when you're expecting to get "1000.00" from a user in North America, you may get "1000,00" from someone in Norway.
This being said, is it typical that numberDecimal localizes like this and allows for the comma? If so, do you know if it limits users to inserting just the last comma? I am asking as I am using the following code to fix this problem, as you can see, it relies on their being just a single comma to replace:
// Required to handle European use of commas instead of decimals places
// in their currency.
edittext_amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable edittext_amount) {
String amount = "";
if (edittext_amount != null) {
try {
amount = edittext_amount.toString().replace(",", ".");
double_edittext_amount = Double.parseDouble(amount);
}
catch (NumberFormatException e) {
// Error
}
}
}
As mentioned, the above code was instituted to prevent the comma from creating an error, the error I receive is as follows:
java.lang.NumberFormatException: Invalid double: "1000,00"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:269)
at java.lang.Double.parseDouble(Double.java:295)
at java.lang.Double.valueOf(Double.java:332)
at com.ootpapps.saving.made.simple.SavingsPlanEditor.validateSavingsPlan(SavingsPlanEditor.java:233)
at com.ootpapps.saving.made.simple.SavingsPlanEditor.access$1(SavingsPlanEditor.java:217)
at com.ootpapps.saving.made.simple.SavingsPlanEditor$2.onClick(SavingsPlanEditor.java:109)
at android.view.View.performClick(View.java:3644)
at android.view.View$PerformClick.run(View.java:14313)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
Thank you for your insight, I hope to settle this once and for all!
Edit - Changed the code to use NumberFormat, as follows:
// Required to handle European use of commas instead of decimals places
// in their currency.
edittext_amount.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable edittext_amount) {
String amount = "";
if (edittext_amount != null) {
try {
amount = edittext_amount.toString();
NumberFormat number_format = NumberFormat.getNumberInstance();
double_edittext_amount = number_format.parse(amount).doubleValue();
}
catch (NumberFormatException e) {
// Error
}
catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is an alternative way to do what you are doing;
String amount = null;
String fist = null;
String second = null;
if (edittext != null){
amount = edittext.to string();
if (amount.contains(","){
StringTokenizer tokens = new StringTokenizer(CurrentString, ",");
first = tokens.nextToken();// this will contain the whole number
second = tokens.nextToken();//this will contain the decimal part
} else if (amount.contains("."){
StringTokenizer tokens = new StringTokenizer(CurrentString, ".");
first = tokens.nextToken();// this will contain the whole number
second = tokens.nextToken();//this will contain the decimal part
}//That bit removed the decimal points, from the strings, now we just put them back together
String fullNumber = first + "." + second;
double_edittext_amount = Double.parseDouble(fullNumber);
Hope this helps
I am fighting with making my app language dependent. The user needs to enter a float. I am using a EditText to display the current value and allow editing.
To prepare I coded:
st = String.format("%.2f", myFloat);
edTxt = (EditText) findViewById(R.id.myEditText);
edTxt.setText(st, TextView.BufferType.EDITABLE);
edTxt.selectAll();
Now the user is presented the value. If in Settings of my device, I set my language to Deutsch (German) an float value of 2.80 is displayed as 2,80. On onPause of the activity I retrieve the value and convert it from string to float - and get a NumberFormatException error because of the comma.
Should be easy I thought, I just need to replace the comma by a dot, and coded:
String st ="";
st = edTxt.getText().toString();
st.replace(",", ".");
try{
float minV = Float.valueOf(st);
} catch (NumberFormatException nfe){
mShowAToast("NumberFormatException: " + st);
}
And surprise: The app runs into the catch and the toast shows st as "2,80" instead of "2.80", st.replace didn't do its job.
(probably it did, but)
Do I oversee anything?
If you have an float value that use ',' as decimal separator. You can parse it using a Locale class. Check the following code.
public static void main(String[] args) {
try {
// Number and NumberFormat are in java.text.*;
Number numberG = NumberFormat.getNumberInstance(java.util.Locale.GERMAN).parse("-1.234,56");
if (numberG instanceof Double) {
System.out.println(">" + numberG.doubleValue());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
It will print:
>-1234.56
So instead of use java.util.Locale.GERMAN you can use the defaul locale: java.util.Locale.getDefault() of your JVM.
About the replace function of String I have compared the specfication of Android API and Oracle JDK and both are the same. So I think it must return what you expected. Just in case I have tried the folowing in my JDK:
String value = "-1.234,56";
System.out.println(value.replace(',', '.'));
System.out.println(value.replace(",", "."));
And both are printing: -1.234.56