Converting TextView value to double variable - android

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

Related

How to convert string value to integer?

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.

Get EditTextValue and parse it into a decimal with only one digit for integer part

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 Avoid Scientific Notation in Double?

Here is my simple code
#Override
public void onClick(View v) {
try {
double price = Double.parseDouble(ePrice.getText().toString());
double percent = Double.parseDouble(ePercent.getText().toString());
double priceValue = price * percent/100.0f;
double percentValue = price - priceValue;
moneyToGet.setText(String.valueOf(priceValue));
moneyToPay.setText(String.valueOf(percentValue));
moneyToGet.setText("" + priceValue);
moneyToPay.setText("" + percentValue);
// catch
} catch (NumberFormatException ex) {
// write a message to users
moneyToGet.setText("");
}
}
});
This is a simple code for Percentage Calculator.
What I want is to avoid the Scientific Notation in my Calculator cause I don't want to explain to user what is Scientific Notation.
For example if I want to calculate 100,000,000 and cut 50% of it, it Should give me 50,000,000 which is giving me 5.0E7 And in my case this doesn't make any sense to the user. And of course I know both results are correct.
Thanks in Advance.
Check answer here. You can write
moneyToGet.setText(String.format("%.0f", priceValue));
You can try this DecimalFormat
DecimalFormat decimalFormatter = new DecimalFormat("############");
number.setText(decimalFormatter.format(Double.parseDouble(result)));
I would suggest using BigDecimals instead of doubles. That way you will have a more precise control over your calculation precision. Also you can get a non-scientific String using BigDecimal.toPlainString().
DecimalFormat decimalFormatter = new DecimalFormat("##.############");
decimalFormatter.setMinimumFractionDigits(2);
decimalFormatter.setMaximumFractionDigits(15);
This option will help you ##.## suffix 0 before decimal, otherwise output will be .000
btc.setText(decimalFormatter.format(btcval));
use this for displaying content
Use NumberFormater like
NumberFormat myformatter = new DecimalFormat("########");
String result = myformatter.format(yourValue);

Android How can I convert String to Double without losing precision? [duplicate]

This question already has answers here:
How can I convert String to Double without losing precision in Java?
(4 answers)
Closed 9 years ago.
i want to develop one calculation base application but getting one problem.
Tried as below
double add_num = 10.06
String data = edittext.getText().toString();
value assign to data is
// data = 1000.06
now i am converting string to double
double amount = Double.parseDouble(data);
// amount = 1000.0
double final_amount = amount + add_num;
// final_amount = 1010.0
getting final_amount is 1000.0 which is not correct because amount value is losing precision i want the correct answer which is 1000.06
please let me know correct way without using format() method
Well, first of all correct value is 1010.12, not 1000.06. And this code:
double add_num = 10.06;
String value = "1000.06";
double amount = Double.parseDouble(value);
double final_amount = amount + add_num;
System.out.println(final_amount);
prints 1010.1199999999999, which is correct.
If you just want to print the number with the desired precision, use one of:
// Prints with two decimal places: "1010.12"
System.out.format("%.2f", final_amount);
System.out.println(String.format("%.2f", final_amount));
// Example, set TextView text with two decimal places:
edittext.setText(String.format("%.2f", final_amount));
By the way, in your code you have:
String data = edittext.getText().toString();
double amount = Double.parseDouble(value); // value?
Shouldn't it be?
double amount = Double.parseDouble(data);
String s="1000.06";
double d=Double.parseDouble(s);
System.out.println(d);
The above code give output: 1000.06
You should use String.ValueOf(double d);
For Example:-
Double to String
String value=String.valueOf(1000.06);
OR
String value=String.valueOf(add_num);
String to Double
Double value=Double.valueOf("1000.06");
OR
Double value=Double.valueOf(add_num);

Convert String to Double excluding part of the string

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;

Categories

Resources