Parsing string to double/float throwing errors - java

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);

Related

calculating numbers after . (dot) in java

I am new to Java. creating calculator which calculates number from user input.
I have 2 Jtextfield in my application where user input numbers.
For example in first field user input 45678.230 and in second field 23214.210 which gives me subtraction result is 22464 but everything i want is full result followed by .(dot) so my answer should be 22464.02
String n1opn = n1open.getText();
String n1clsd = n1close.getText();
double n1intopen = (int) Double.parseDouble(n1opn);
double n1intclose = (int) Double.parseDouble(n1clsd);
double n1ltr = n1intclose - n1intopen;
System.out.println("output "+ n1ltr);
You seem to be casting your inputs to an int. Integers don't have any decimal bits so using double is correct for your case!

String decimal to percentage in java [duplicate]

This question already has answers here:
java how to make user friendly percentage output from float number
(9 answers)
Closed 2 years ago.
I have a string value as below:
String percValue = "0.0209"
How can I convert this to something like as below
String formatedValue = "2.09%";
Can someone help me what is the simple and best way to convert this?
One good way would be to:
convert your percentage string to a number (needs to be a double type variable, so it can hold the decimal places...),
multiply the value by 100 to make it a percentage,
re-format the number in a string.
String percValue = "0.0209";
double percentage = Double.parseDouble(percValue) * 100;
String formattedValue = String.format("%.2f%%", percentage);
Explanation:
Double.parseDouble() takes your string as a parameter and returns a double value which you can do things like multiplication and addition with, and
String.format() lets you precisely control how your number is converted back to a String!
"%.2f" means "Take the next argument which is a floating-point variable and put it here, with two decimal places".
"%%" means "print a single '%'". You need two to "escape" it, since percent symbols are not literally interpreted in format strings.
You should parse the String into a double, multiply by 100, and then append the % sign to it as follows:
String percValue = "0.0209";
double per = Double.parseDouble(percValue);
String percentage = (per*100)+"%";
You need to parse your string value and then multiply by 100, something like this:
String percValue = "0.0209";
double value = ( Double.parseDouble(percValue)) * 100;
String formatedValue = value + "%";
Convert String to BigDecimal(for Big numbers) and multiply by 100.
String percValue = "0.0209";
BigDecimal temp=new BigDecimal(percValue).multiply(BigDecimal.valueOf(100)).stripTrailingZeros();
String formatedValue =temp.toString() + "%";

How to convert a string with multiple points to double in android

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(",", "");

How to print formatted double value to string in java?

I want to create a String from a double value with 10 character for example
Double d = 150.23;
The output string like this 0000015023+
I have used this code but it is not working:
String imponibile = String.format("%10d%n", myDoubleValue);
You want to print 150.23 without the period. Formatting is not supposed to achieve that. You have to:
transform the double number to a int number with the desired rounding and print the int:
int i = (int) Math.round(100.0 * d);
String.format("%010d", i)
Where "010" means print at least 10 digits and pad with zero if there are less. The padding char going before the number of digits.
print the double and remove the period from the string afterwards:
String.format("%011.2f", d).replace(".", "")
Note how you now have to specify 11 including the period. And you have to specify the number of digits after the period
I don't think there is a way to print the sign after a number with String.format. You can easily require to print it at the start which is the normal way to print numbers:
String s = String.format("%+010d", i);
And if you must you can use substring and concatenation to put it at the end:
String imponibile = s.substring(1) + s.charAt(0);
Try f instead of d:
String imponibile = String.format("%010.0f", myDoubleValue*100);
Floating Point - may be applied to Java floating-point types: float,
Float, double, Double, and BigDecimal
Class Formatter

How to convert a String number to two three decimal places in Java?

I am trying to convert a String number to two decimal places in Java. I saw lot of posts on satckoverflow but somehow I am getting an exception.
String number = "1.9040409535344458";
String result = String.format("%.2f", number);
System.out.println(result);
This is the exception I am getting -
java.util.IllegalFormatConversionException: f != java.lang.String
I would like to have 1.904 as the output. Does anyone know what wrong I am doing here?
You can try using a NumberFormat. For example:
String number = "1.9040409535344458";
NumberFormat formatter = new DecimalFormat("#0.000");
String result = formatter.format(Double.valueOf(number));
System.out.println(result);
Just declare number to be double :
Double number = 1.9040409535344458;
instead of
String number = "1.9040409535344458";
OUTPUT :
1.90
you should first convert the string into double and then change the decimal value
String number = "1.9040409535344458";
double result = Double.parseDouble(number);//converts the string into double
result = result *100;//adjust the decimal value
System.out.println(result);
You are using a format not meant for a String. I would recommend either converting your String to a double or storing it as a double in the first place. Convert the String to a double, and pass that double to String.format.

Categories