How to parse numerical values from a string? - java

How do I convert String in form xx:yy into integer form xxyy or float form xx.yy
For example If I have the following string.
String x = "10:30"
How do I get integer 1030 or float value 10.30 ?

String[] parts = x.split(":");
float value = Integer.parseInt(parts[0]) + (float)Integer.parseInt(parts[1])/100;
or
Float.parseFloat(x.replaceAll(":", "."));

String xInt = x.replace(":","");
Integer.parseInt(xInt);
String xFloat = x.replace(":",".");
Float.parseFloat(xFloat);

Related

Getting NumberFormat while trying to parse a string

I'm trying to parse a string to an integer. The string is a number when I do sys out but when I try to parse it then it adds a double quote at the beginning. I'm not doing anything additional.
Following is a snippet of my code:
System.out.println("Result 2 is: "+results[2]);
String temp = results[2].replace("\"", "");
System.out.println("String Temp is: "+temp);
int height = Integer.parseInt(results[1].replace("\"", ""));
int width = Integer.parseInt(results[2].replace("\"", ""));
In the logs:
String Temp is: 2550
wt.system.err wcadmin - java.lang.NumberFormatException: For input string: "2550
This exception is only for result[2]. Something to do with character set?
Option 1: Parse temp. Change
int width = Integer.parseInt(results[2].replace("\"", ""));
to
int width = Integer.parseInt(temp);
Option 2: Use a regular expression to remove everything not a digit instead of trying to handle corner cases by hand.
int width = Integer.parseInt(results[2].replaceAll("\\D+", ""));

How to convert string with $ sing in it to int

I have a string "$1,076.00" and I want to convert them in to int,
I capture some value $1,076.00 and saved in string called originalAmount,
and tried int edited = Integer.parseInt(originalAmount); and it gave me error java.lang.NumberFormatException: For input string: "$1,076.00"
can anyone help?
You need to remove the undesired part ($ sign) and then parse the string to double carefully since the decimal part is a locale dependent
String pay = "$1,076.00";
NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse(pay.replace("$", ""));
double result = number.doubleValue();
System.out.println(result);
string sourceString = "$1,076.00";
sourceString.substring(1, sourceString.length() - 1)
int foo = Integer.parseInt(sourceString);
Try this:
String amount = "$1,076,.00";
String formatted = amount.replace("$", ""); // remove "$" sign
formatted = formatted.replace(",", ""); // remove "," signs from number
double amountDouble = Double.parseDouble(formatted); // convert to double
int amountInt = (int)amountDouble; // convert double value to int
System.out.println(amountInt); // prints out 1076
String originalAmount="$1076.00";
String amount = originalAmount.replace($,"");
int edited = Integer.parseInt(amount);
Thanks everyone yr answers help me a lot
I have come up with
originalAmount = originalAmount.substring(1);
if (originalAmount.contains("$")) {
originalAmount = originalAmount.replace("$", "");
}
newOriginalAmt = Double.parseDouble(originalAmount);
System.out.println(newOriginalAmt);
pls let me know yr thoughts

Conversion of double to string gives exponent values

I am trying to convert a string 32,646,513.32 to a double and then convert it to a string in scientific notation like this 3.264651332E7. The code below is
double amount = 0;
for (Payments payments : pvor.getPayments()) {
payments.setDocumentNumber(pvor);
amount += Double.parseDouble(payments.getAmount());
payments.setDate(new Date());
}
DecimalFormat df = new DecimalFormat("#.00");
double totalAMount = Double.valueOf(df.format(amount));
Double totalAMounts = (Double) totalAMount;
pvor.setAmount(String.valueOf(totalAMounts.doubleValue()));
How do I display large numbers in same format as I give?
Instead of using just String.valueOf(totalAmounts), which give you number in exponential format, you need to format your double value to match the string format that you want. Try something like new DecimalFormat("#,###.00").format(totalAmounts). Or simply use String.format("%,.2f", totalAMounts).
If I understood your problem correctly then you do not need String.valueOf() but String.format().
Here is the code snippet:
public static void main (String[] args) throws Exception
{
String input = "32,646,513.32";
double value = Double.parseDouble(input.replace(",",""));
String output = String.format("%f",value);
System.out.println("Value: " + output);
}
Output:
Value: 32646513.320000
Replace the following line in your code appropriately:
/* Note the change from `valueOf()` to `format()` */
pvor.setAmount(String.format("%f",totalAMounts.doubleValue()));

Convert $16500.00 String to 16500 Integer

Im having an issue trying to convert $16500.00 String to 16500 Integer.
This is what i have at the moment but its failing with:
FATAL EXCEPTION: main
java.lang.NumberFormatException: Invalid int: "[]"
The code i have is:
String depTest = mDepositAmount.getText().toString();
String deptest2 = Arrays.toString(depTest.replace("R", "").replace(",", "").split("."));
int dep = Integer.parseInt(deptest2);
Please could you help me with getting the end result to 16500. I know how to convert it to int by using Integer.parseInt its just im struggling to get the end result to be 16500 in String
Does your original string always starts with character '$' and followed by number format?
If so try this one:
String org = "$16500.00";
String numbersOnly = org.substring(1); // "16500.00"
int yourInteger = (int)(Float.parseFloat(numbersOnly));
// if you need String, convert it to String again
String integerString = Integer.toString(yourInteger);
You could use a DecimalFormat
import java.text.*;
NumberFormat nf = new DecimalFormat("$0.00");
int value = (int) nf.parse("$16500.00");
You can try with this
String getValue = "$16500.00";
String removeFirstCharecter = getValue.substring(1); // "16500.00"
String [] getString = removeFirstCharecter.split("\\.");
String firstIntValue = (getString[0]); //16500
String sirstIntValue = (getString[1]); //00
Now you can convert firstIntValue String to Integer .
String getRequiredValue = Integer.toString(firstIntValue); //16500
It may be happen because of $ sign so, Just take one another Text view only for Price 16500 and other for $ sign. then convert the Integer.parseInt(textview.getText().toString);

Convert string to float: "8.9km" to float

I'm getting the distance in string like "8.9km". I need to convert it to float.
So if the string is "8.9km", the corresponding float will be 8.9
How to achieve this in Java?
Note: The value can change to miles/meters also, since it is retrieved from Google Maps
You can try the following code,
String dis = "8.9km";
Float distance = Float.valueof(dis.substring(0,dis.indexOf("km")));
float d = distance.floatValue();
You can do
String distance = "8.9km";
float distanceInFloat = Float.parseFloat(distance.substring(0,distance.indexOf("km")));
System.out.println(distanceInFloat);
Output :
8.9
Use following code:
String s="8.9km";
s=s.replace("km", "");
float f=Float.parseFloat(s);
System.out.println(f);
Output:
8.9
Hope it helps.
try the following for removing all non-digits(excluding '.') from a string
String distance = "7.9km";
float floatValue = Float.parseFloat(distance.replaceAll("[^\\d.]",""));
System.out.println(floatValue);
String str = "8.9km";
str = (str.replace("km", ""); //remove the km
float f = Float.parseFloat(str); //convert the string to a float
The float f will now have a value of 8.9
System.out.println(f);
Output:
8.9
Try this:
public float parse(String string, String suffix) { // suffix can be m, km etc.
if (!string.endsWith(suffix)) {
throw new IllegalArgumentException();
}
string = string.subString(0, string.length() - suffix.length()); // get rid of the suffix we have at the end
return Float.parseFloat(string); // parse the float from what we have left
}
If the float is invalid, or the string doesn't end in "km", a NumberFormatException or IllegalArgumentException will be thrown, respectively.
Try this.. i hope it will help
String km = "8.9km";
float kmInFloat=Float.parseFloat(km.replaceAll("km",""));
System.out.println(kmInFloat);
Output :
8.9

Categories

Resources