Convert String to double - android

Is there way to convert a string to double. This is how i did.
String s = b.getText().toString();
double d = Double.parseDouble(s);
It gives NumberFormatException

Try this
String s = b.getText().toString();
double d = Double.valueOf(s.trim()).doubleValue();

You are probably starting off with a zero-length string. Check the length before you parse it. It also wouldn't hurt to catch NumberFormatException, although that shouldn't be problem if you have android:inputType="number" in the view's layout.
double d = 0;
CharSequence cs = b.getText();
if(cs != null && cs.length() > 0) {
d = Double.parseDouble(cs.toString());
}

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

calculate percentage and display in a texview android studio

I am developing an application where I pass 1 variables int through a string of an activity to next activity, in the next activity I take that string and return it again and an int, then I calculate a percentage and display and a textview, the past variable and approx1 so I check if it is not empty, then I calculate the percentage ex: ((3/45) * 100) and display in a text view, reviewing again for string ... but in any way I make a mistake, what can be ?
Bundle bundle = getIntent (). GetExtras ();
String aprox1 = bundle.getString ("aprox1");
if (aprox1! = null)
try {
num3 = Integer.parseInt (aprox1);
 result = Math.round ((num3 / 45) * 100);
 TextView counter2 = (TextView) findViewById(R.id.textView16);
String abcString2 = Integer.toString (result);
counter2.setText (abcString2);
}
 catch (NumberFormatException e) {
 }
You need to have {} after the if statement like so:
if (aprox1! = null) {
try {
num3 = Integer.parseInt (aprox1);
result = Math.round ((num3 / 45) * 100);
TextView counter2 = (TextView) findViewById(R.id.textView16);
String abcString2 = Integer.toString (result);
counter2.setText (abcString2);
}
catch (NumberFormatException e) {
}
}
Its also worth noting that because num3 is an integer when you divide it by 45 you will get an Integer not a percentage.
To fix this issue, make num3 a double or cast either num3 or 45 to a double before computing the division.
For example, a simple fix would include changing line 4 to the following:
result = Math.round ((num3 / 45.0) * 100);

Convert String from Shared Preferences to Double Value

I've been trying to convert the following string to double value from my Shared Preferences key but still failed even I've tried to follow the solution from the previous Q&A (Android - SharedPreference converting to Double)
Here are my code:
String strCurr_Lat = FM_SharePrefs.getString("FM_Curr_Lat", "");
String strCurr_Lng = FM_SharePrefs.getString("FM_Curr_Lng", "");
String strDest_Lat = FM_SharePrefs.getString("FM_Dest_Lat", "");
String strDest_Lng = FM_SharePrefs.getString("FM_Dest_Lng", "");
Double dCurr_Lat = Double.parseDouble(strCurr_Lat);
Failed and throw an error when reach the assign double variable.
Can anyone assist? Thank you very much.
-sea-
Try this :)
Double dCurr_Lat = Double.valueOf(strCurr_Lat);
To parse in double your string need to in floating number formate. So first you have to check whether it is or not , Otherwise it will throw NumberFormatException .
String strCurr_Lat = FM_SharePrefs.getString("FM_Curr_Lat", "");
if(!TextUtils.isEmpty(strCurr_Lat)){
try {
Double curr_Lat = Double.parseDouble(strCurr_Lat);
}catch (NumberFormatException e){
e.printStackTrace();
Log.e("Parse","String not in floating format");
}
}
if your value is not null then try this it will work.
double dCurr_Lat= Double.parseDouble(strCurr_Lat);

How to add Comma between numbers

I have this code for my calculator:
public void onClick(View v) {
try {
double price = Double.parseDouble(InputPrice.getText()
.toString());
double percent = Double.parseDouble(InputPercent.getText()
.toString());
double priceValue = price * percent / 100.0f;
double percentValue = price - priceValue;
PriceToGet.setText(String.valueOf(priceValue));
PriceToPay.setText(String.valueOf(percentValue));
PriceToGet.setText(String.format("%.02f", priceValue));
PriceToPay.setText(String.format("%.02f", percentValue));
The Input and the Output are coming without commas like this:
Input: 333333333
Output: 134555.44
Output: 17475.66
This was just an example for Output and Input.
How do I like the user see them is:
Input: 333,333,333
Output: 134,555.44
Output: 17,475.66
Thanks
Update:
I added decimal in my onclick code:
DecimalFormat formatter = new DecimalFormat("#,###,###");
I used this code but its closing the App after I press the button:
String PriceToGet = formatter.format(String.format("%.02f", priceValue));
And when I am using this method:
String PriceToGet = formatter.format("%.02f", priceValue);
Its force me to change it to:
String PriceToGet = formatter.format(priceValue);
What to do?
You need to use DecimalFormat
You will find the complete answer here
This is how you can convert one of your integers to strings.
int x = 1000000;
DecimalFormat formatter = new DecimalFormat("#,###,###");
String number_string = formatter.format(x);
System.out.println(number_string);
// Outputs 1,000,000
This JS function from Css Tricks - http://css-tricks.com/snippets/javascript/comma-values-in-numbers/
function CommaFormatted(amount) {
var delimiter = ","; // replace comma if desired
var a = amount.split('.',2)
var d = a[1];
var i = parseInt(a[0]);
if(isNaN(i)) { return ''; }
var minus = '';
if(i < 0) { minus = '-'; }
i = Math.abs(i);
var n = new String(i);
var a = [];
while(n.length > 3) {
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if(n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
if(d.length < 1) { amount = n; }
else { amount = n + '.' + d; }
amount = minus + amount;
return amount;
}

unable to parse "" as integer[FC]

I have this code to control if a EditTextPreference is null or not:
case R.id.prochain_vidange:
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String choix_huile = settings.getString("listPref_huile_moteur", "0");
km = settings.getString("km", "");
Log.d("TAG",km);
int x= Integer.valueOf(km);
if (km != "")
{
if (Integer.valueOf(choix_huile) == 0) {
............
The problem is in this line:
int x= Integer.valueOf(km);
What could be the problem ?
Thanks.
If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:
km = settings.getString("km", "0");
Alternatively, you can catch the exception, and set x to 0:
km = settings.getString("km", "");
int x;
try {
x = Integer.valueOf(km);
} catch(NumberFormatException e) {
x = 0;
}
Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException
You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".
before:
int x= Integer.valueOf(km);
if (km != "") {
after:
if (km != "") {
int x= Integer.valueOf(km);
Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.
However, wrapping it in a try { } catch() block is not an approach I would recommend.
The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:
km = settings.getString("km", "0");
Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.
Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.

Android: converting String to int

I'm simply trying to convert a string that is generated from a barcode scanner to an int so that I can manipulate it by taking getting the remainder to generate a set number of integers. So far I have tried:
int myNum = 0;
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
}
and
Integer.valueOf(mystr);
and
int value = Integer.parseInt(string);
The first one gives me the error :The method getText() is undefined for the type String
while the last two don't have any compile errors but the app crashes immediately when those are called. I thought it had to do with my barcode scanning intent method but I put it into the OnCreate and still got the error.
Change
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
to
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
It's already a string? Remove the getText() call.
int myNum = 0;
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
// Handle parse error.
}
You just need to write the line of code to convert your string to int.
int convertedVal = Integer.parseInt(YOUR STR);
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""))
output: i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=((Number)NumberFormat.getInstance().parse(s)).intValue()
output: i=123;
barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int. you can use BigInteger
BigInteger reallyBig = new BigInteger(myString);
You can not convert to string if your integer value is zero or starts with zero (in which case 1st zero will be neglected).
Try change.
int NUM=null;
try this
String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());
boolean ins = myDB.adddata(t1,t2);
public boolean adddata(String name, Integer price)
// Convert String to Integer
// String s = "fred"; // use this if you want to test the exception below
String s = "100";
try
{
// the String to int conversion happens here
int i = Integer.parseInt(s.trim());
// print out the value after the conversion
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}

Categories

Resources