When I run the following script to check inputQty greater than AvailQty I am getting the following:
java.lang.NumberFormatException: For input string: "97,045.1193"
This error occurs if availableQty is a decimal number. The value is delivered from a database, can you please correct where I am wrong?
double AvailQty = Double.valueOf(AQTY.getValue());
double inputQty = Double.valueOf(QTY.getValue());
if(inputQty > AvailQty){
session.setStatusMessage("Not Enough Quantity");
//Abort operation
throw new AbortHandlerException();
}
Thanks
Your string contains commas, remove any commas before parsing.
Double.valueOf(INV.AVAILQTY.getValue().replaceAll(",", ""));
It can't format it because it doesn't accept the comma. You could do something like Double.valueOf(INV.AVAILQTY.getValue().replaceAll(",", "")) and Double.valueOf(XX_IGL_QTY.getValue().replaceAll(",", "")) to remove any commas before parsing.
Simple, your string contains commas. This is not legal. All you can have are numbers and a dot (decimal separator).
I don't know where you get the value from, but if it's not something you can change on that side, you will have to do some hacking ;)
Double.valueOf(INV.AVAILQTY.getValue().replaceAll(",","");
Rather than re-formatting the string to do the conversion, you can tell the formatter to read the numbers using whatever format you like.
This answer shows how to change the formatting.
Here's a sample test to show how the same number in your question can be parsed successfully:
#Test
public void showNumberFormats() throws ParseException {
String rawAvailQty = "97,045.1193";
String rawInptQty = "98,045.3421";
NumberFormat nf = NumberFormat.getNumberInstance();
double AvailQty = nf.parse(rawAvailQty).doubleValue();
double inputQty = nf.parse(rawInptQty).doubleValue();
if(inputQty > AvailQty){
//Abort operation
System.err.println("Could not perform operation");
}
System.out.println("Available qty: " + AvailQty);
System.out.println("Input qty: " + inputQty);
}
Prints:
Could not perform operation
Available qty: 97045.1193
Input qty: 98045.3421
Related
I have a user string generated by some computations. The user string is "3.2E7"
It is written in Scientific Notation. I need to convert it to standard notation because
the drawing instructions on the App overlap if it reads a Scientific Notation number.
I do know how to convert it to Standard Notation use the Number class, as the following shows:
String generated = "3.2E7"
try{
NumberFormat format = NumberFormat.getInstance();
Number my_number = format.parse(generated);
System.out.println("see my number: " + my_number); //this prints correctly: 32000000
}catch(Exception exception){
Log.d("see009",""+exception);
}
Now, the problem I am having is that if the variable 'generated' < 1 but greater than zero. Then, the NumberFormat class does not convert it properly:
String generated = "3.2E-7";
//inside the try catch block from above:
System.out.println("see my number: " + my_number); //this prints 3.2E-7 NOT: 0.00000032
Doesn't the Number class accept non-integers. How can I make the NumberFormat object format the Scientific notation number less than 1?
Working with the BigDecimal class I have been able to overcome the problem:
Simply do this:
String generated = "3.2E7";
BigDecimal big_decimal = new BigDecimal(generated);
System.out.println("look at this: " + big_decimal.toPlainString()); //will print: 32000000
generated = "3.2E-7";
big_decimal = new BigDecimal(generated);
System.out.println("look at this: " + big_decimal.toPlainString()); //will print: 0.00000032
BigDecimal even worked with powers in the magnitude of 20. It is a very efficient solution that is good for my needs.
I'm taking a value from the mobile application which I'm getting in string format something like "$000"(which actually $0.00 ) similarly I want to convert all the value into two decimal place say if I get "$279"(which is in application actually $2.79)
I don't know the correct approach because further in I have compair this value to some other string.
so I want to keep this as String but at the same time I want to put decimal after two place always whatever the number.
I tried to Decimal formatter for money but gave me "object as a number format" exception
sends
String accLastFourDigits, getCurrAmt, currAmt;
getCurrAmt = getDriver().findElement(by("overview.current_balance")).getText();
DecimalFormat money = new DecimalFormat("$0.00");
currAmt = money.format(getCurrAmt);
You could use builtin NumberFormat provided by JAVA to parse different country Currencies as shown below. Also I am dividing the resulting number by 100, so as to satisfy the requirement, that $978 is read as 9.78.
NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);
String currencyValue = "$100";
try {
System.out.println(usFormat.parse(currencyValue).intValue()/100);
}catch(ParseException e) {
e.printStackTrace();
}
Here, I am setting the currency to US and then parsing a string with dollar sign.
You could also use the format method of NumberFormat to print the currency value in respective currency formats, as shown below
NumberFormat usFormat = NumberFormat.getCurrencyInstance(Locale.US);
String currencyValue = "$100";
try {
Number value = usFormat.parse(currencyValue).intValue()/100;
System.out.println("Number value : " + value);
System.out.printf("In Currency : "+usFormat.format(value));
}catch(ParseException e) {
e.printStackTrace();
}
You have this exception because format method expect number type argument. What you need to do then is to remove all non digits characters from the input string
getCurrAmt = getCurrAmt.replaceAll("[^\\d.]", ""); // please note that replaceAll method has poor performance
and parse it to Integer when calling format method
money.format(Integer.parseInt(getCurrAmt))
As pointed out replaceAll method is not very efficient because it needs to compile Pattern every single time and it's better to use Matcher - you can read about this in this topic:
String replaceAll() vs. Matcher replaceAll() (Performance differences)
How about this?
String inputStr = "$279";
NumberFormat usCurrency = NumberFormat.getCurrencyInstance(Locale.US);
usCurrency.setParseIntegerOnly(true);
long num = (Long)usCurrency.parse(inputStr);
BigDecimal amount = new BigDecimal(num);
amount = amount.scaleByPowerOfTen(-2);
log.info("amount: {}", usCurrency.format(amount));
I have a string "3,350,800" with multiple points I want to convert to double but have error multiple points
String number = "3,350,800"
number = number.replace(",", ".");
double value = Double.parseDouble(number);
Error : java.lang.NumberFormatException: multiple points
The . character is used as a decimal point in English, and you cannot have more than one of those in a number.
It seems like you're using it as a thousands separator though. This is legal in several locales - you just need to use one that allows it, e.g.:
String number = "3.350.800";
NumberFormat format = NumberFormat.getInstance(Locale.GERMAN);
double value = format.parse(number).doubleValue();
Mix of other answers, no reason to change the , for . and then fetch the German local.
String number = "3,350,800";
NumberFormat format = NumberFormat.getInstance();
double value = format.parse(number).doubleValue();
System.out.println(value);
Output:
3350800.0
you need to use something like this :
String number = "3,350,800";
number = number.replaceAll(",", "");
double value = Double.parseDouble(number);
System.out.println(value);
What number are you trying to get?
3.350.800 is what you're trying to parse as a double,
but that's obviously not a number, since there are "multiple points".
If you just wanna get 3,350,800 as your number, simply change this line -
number = number.replace(",", ".");
to this -
number = number.replace(",", "");
I am extracting couple of values like 1234, 2456.00 etc from UI as string. When I try to parse this string to float, 1234 is becoming 1234.0 and when I tried to parse as double its throwing error. How can I solve this?
I am using selenium web driver and java. Below are few things I tried.
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
I think you mixed it up a bit when trying to figure out how to parse the numbers. So here is an overview:
// lets say you have two Strings, one with a simple int number and one floating point number
String anIntegerString = "1234";
String aDoubleString = "1234.123";
// you can parse the String with the integer value as double
double integerStringAsDoubleValue = Double.parseDouble(anIntegerString);
System.out.println("integer String as double value = " + integerStringAsDoubleValue);
// or you can parse the integer String as an int (of course)
int integerStringAsIntValue = Integer.parseInt(anIntegerString);
System.out.println("integer String as int value = " + integerStringAsIntValue);
// if you have a String with some sort of floating point number, you can parse it as double
double doubleStringAsDoubleValue = Double.parseDouble(aDoubleString);
System.out.println("double String as double value = " + doubleStringAsDoubleValue);
// but you will not be able to parse an int as double
int doubleStringAsIntegerValue = Integer.parseInt(aDoubleString); // this throws a NumberFormatException because you are trying to force a double into an int - and java won't assume how to handle the digits after the .
System.out.println("double String as int value = " + doubleStringAsIntegerValue);
This code would print out:
integer String as double value = 1234.0
integer String as int value = 1234
double String as double value = 1234.123
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234.123"
Java will stop "parsing" the number right when it hits the . because an integer can never have a . and the same goes for any other non-numeric vales like "ABC", "123$", "one" ... A human may be able to read "123$" as a number, but Java won't make any assumptions on how to interpret the "$".
Furthermore: for float or double you can either provide a normal integer number or anything with a . somewhere, but no other character besides . is allowed (not even , or ; and not even a WHITESPACE)
EDIT:
If you have a number with "zeros" at the end, it may look nice and understandable for a human, but a computer doesn't need them, since the number is still mathematically correct when omitting the zeros.
e.g. "123.00" is the same as 123 or 123.000000
It is only a question of formatting the output when printing or displaying the number again (in which case the number will be casted back into a string). You can do it like this:
String numericString = "2456.00 "; // your double as a string
double doubleValue = Double.parseDouble(numericString); // parse the number as a real double
// Do stuff with the double value
String printDouble = new DecimalFormat("#.00").format(doubleValue); // force the double to have at least 2 digits after the .
System.out.println(printDouble); // will print "2456.00"
You can find an overview on DecimalFormat here.
For example the # means "this is a digit, but leading zeros are omitted" and 0 means "this is a digit and will not be omitted, even if zero"
hope this helps
Your first problem is that "SOQ" is not a number.
Second, if you want create a number using a String, you can use parseDouble and give in a value that does not have a decimal point. Like so:
Double.parseDouble("1");
If you have a value saved as a long you do not have to do any conversions to save it as a double. This will compile and print 10.0:
long l = 10l;
double d = l;
System.out.println(d);
Finally, please read this Asking a good question
The problem is you cannot parse non-numeric input as a Double.
For example:
Double.parseDouble("my text");
Double.parseDouble("alphanumeric1234");
Double.parseDouble("SOQ");
will cause errors.
but the following is valid:
Double.parseDouble("34");
Double.parseDouble("1234.00");
The number you want to parse into Double contains "," and space so you need first to get rid of them before you do the parsing
String str = "1234, 2456.00".replace(",", "").replace(" ", "");
double Val=Double.parseDouble(str);
I'm getting NumberFormatException when I try to parse 265,858 with Integer.parseInt().
Is there any way to parse it into an integer?
Is this comma a decimal separator or are these two numbers? In the first case you must provide Locale to NumberFormat class that uses comma as decimal separator:
NumberFormat.getNumberInstance(Locale.FRANCE).parse("265,858")
This results in 265.858. But using US locale you'll get 265858:
NumberFormat.getNumberInstance(java.util.Locale.US).parse("265,858")
That's because in France they treat comma as decimal separator while in US - as grouping (thousand) separator.
If these are two numbers - String.split() them and parse two separate strings independently.
You can remove the , before parsing it to an int:
int i = Integer.parseInt(myNumberString.replaceAll(",", ""));
If it is one number & you want to remove separators, NumberFormat will return a number to you. Just make sure to use the correct Locale when using the getNumberInstance method.
For instance, some Locales swap the comma and decimal point to what you may be used to.
Then just use the intValue method to return an integer. You'll have to wrap the whole thing in a try/catch block though, to account for Parse Exceptions.
try {
NumberFormat ukFormat = NumberFormat.getNumberInstance(Locale.UK);
ukFormat.parse("265,858").intValue();
} catch(ParseException e) {
//Handle exception
}
One option would be to strip the commas:
"265,858".replaceAll(",","");
The first thing which clicks to me, assuming this is a single number, is...
String number = "265,858";
number.replaceAll(",","");
Integer num = Integer.parseInt(number);
Or you could use NumberFormat.parse, setting it to be integer only.
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html#parse(java.lang.String)
Try this:
String x = "265,858 ";
x = x.split(",")[0];
System.out.println(Integer.parseInt(x));
EDIT :
if you want it rounded to the nearest Integer :
String x = "265,858 ";
x = x.replaceAll(",",".");
System.out.println(Math.round(Double.parseDouble(x)));