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;
Related
I try to get only this part "9916-4203" in "Region Code:9916-4203 " in android. How can I do this?
I tried below code, I used substring method but it doesn't work:
firstNumber = Integer.parseInt(message.substring(11, 19));
If you know that string contains "Region Code:" couldn't you do a replace?
message = message.replace("Region Code:", "");
Assumed that you have only one phone number in your String, the following will remove any non-digit characters and parse the resulting number:
public static int getNumber(String num){
String tmp = "";
for(int i=0;i<num.length();i++){
if(Character.isDigit(num.charAt(i)))
tmp += num.charAt(i);
}
return Integer.parseInt(tmp);
}
Output in your case: 99164203
And as already mentioned, you won't be able to parse any String to Integer in case there are any non-digit characters
Im going to guess that what you want to extract is the full region code text minus the title. So maybe using regex would be a good simple fit for you?
String myString = "Region Code:9916-4203";
String match = "";
String pattern = "\:(.*)";
Pattern regEx = Pattern.compile(pattern);
Matcher m = regEx.matcher(myString);
// Find instance of pattern matches
Matcher m = regEx.matcher(myString);
if (m.find()) {
match = m.group(0);
}
Variable match will contain "9916-4203"
This should work for you.
Java code sourced from http://android-elements.blogspot.in/2011/04/regular-expressions-in-android.html
In Java the substring() method works with the first parameter being inclusive and the second parameter being exclusive. Meaning "Hello".substring(0, 2); will result in the string He.
In addition to excluding the parsing of something that isn't a number like #Opiatefuchs mentioned, your substring method should instead be message.substring(12, 21).
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 getting below error while converting String array to Long array.
java.lang.NumberFormatException: Invalid long: "5571.329849243164". How to round off this value like 5571.
Use this
String.format("%.2f", d)
//try this way, hope this will help you...
String value = "5571.329849243164";
Toast.makeText(MyActivity.this,""+Math.round(Double.parseDouble(value)),Toast.LENGTH_SHORT).show();
round(Double value)`
see here
String string = "5571.329849243164";
Double value1 = Double.parseDouble(string);
tv.setText(Math.round(value1) + "/");
I understand you want to convert a String representing a floating point value to an Integer with rounding, not truncation. Perfectly reasonable.
Two choices.
Convert the string to a Double first (Double.valueOf()), then convert to Integer (intValue()) using a rounding algorithm. Usually it's enough to just add 0.5 to the Double.
Round the String using string operations, then convert to Integer. Split the string at the first ".", convert it to Integer (getInteger()). If the digit after the "." is in the range 5-9 then add one.
I'm sure you can write the code.
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
I have double amount. Let amount to be 500000.12. I want to set value of the amount to TextView like this format 500,000.12 (where 12 is cents , 500,000 is dollars).
I wrote this function and it works
private String getAmountAsString(double amount) {
double integralPart = amount % 1;
int fractionalPart = (int) (amount - integralPart);
int integral = (int) integralPart * 100;
String strFractional = String.format("%,d", fractionalPart);
String strAmount = (strFractional + "." + String.valueOf(integral));
return strAmount;
}
But I think that there can be some easy and good way of doing this with java native functions. Can anybody help to find functions or some better way?
various Locale can be used to format float, double etc. You can use:
String.format(Locale.<Your Locale>, "%1$,.2f", myDouble);
Here .2f represents how many digits you want after decimal. If you are not specifying any locale it will use the default locale.
In String class this method is overloaded as:
format(String format, Object... args)
&
format(Locale l, String format, Object... args)
For more info have a look: Link1 , Link2 and Link3
Therefore NumberFormats are used. They are good to handle local differents for different countries.
//define a local, gets automated if a point or comma is correct in this Country.
NumberFormat anotherFormat = NumberFormat.getNumberInstance(Locale.US);
DecimalFormat anotherDFormat = (DecimalFormat) anotherFormat;
anotherDFormat.applyPattern("#.00");//set the number of digits afer the point
anotherDFormat.setGroupingUsed(true);// set grouping
anotherDFormat.setGroupingSize(3);//and size of grouping
double myDouble = 123456.78;
String numberWithSeparators = anotherDFormat.format(myDouble);//convert it
I think you have to take a look at this one
http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html