Convert exponential string value to double - Java - java

I've an exponential string value
String str = "2.00000181334612E15";
And I'm trying to convert it to a double value.
Double d = (Double.parseDouble(str));
But am getting an Exception as follows,
Exception in thread "main" java.lang.NullPointerException
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1047)
at java.lang.Double.parseDouble(Double.java:521)
at com.swissre.lhrte.poi.test.TestClient.main(Test.java:133)
What am I doing wrong?

There is no problem in your code. To see this, consider this code segment:
public class exp {
public static void main(String[] args) {
String str = "2.00000181334612E15";
Double d = (Double.parseDouble(str));
System.out.println(d);
}
};
If you are getting a NullPointerException from Double.parseDouble then it means that you gave it a null argument. The code lines in your answer don't give it a null argument. So I guess in your full code you must be giving Double.parseDouble a null argument without you realizing it.
According to the Double.parseDouble() documentation, it calls Double.valueOf() and the documentation of Double.valueOf() specifies that you may give it exponential values.

Related

Why am I getting an error when checking if a string can be an double [duplicate]

This question already has answers here:
What is a NumberFormatException and how can I fix it?
(9 answers)
Closed 4 years ago.
Hey guys im pretty new to coding but one of my projects is to check to see if a string can be parse into a double. It keeps printing an error when trying running the program.
Here is the code:
public static void main(String[] args) {
SimpleReader in = new SimpleReader1L();
SimpleWriter out = new SimpleWriter1L();
// Constant entered in by user as a string
out.println("Welcome to constant approximator");
out.println("Please enter in a constant to be estimated");
String realConstant = in.nextLine();
//Double variable created in order to reassign later
double test = 0;
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
//Test reassign and converts
test = Double.parseDouble(realConstant);
out.print(test);
in.close();
out.close();
}
}
Here is the error:
Exception in thread "main" java.lang.NumberFormatException: For input string: "pi"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at ABCDGuesser1Test.main(ABCDGuesser1Test.java:36)
It happens because you type pi which is not recognized as π (pi) constant. What have you typed was a String and these characters are not convertible to a number.
If you want to enter any number including the special constant like pi, you have to check first if the input is a Number or String. In case it's String, you can try to match it with a defined constant like π or e and use their defined value in Java such as Math.PI.
You should use the result of canParseDouble() not just call it. Something like this, I think:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
As you say:
//FormatChecker class and canParseDouble verifies if the string is truly a double. boolean method.
FormatChecker.canParseDouble(realConstant);
You know that this line calls a boolean method and will then return either true or false. However, you do not do any use of this returned value. If so, what's the point of even calling the function, right?
You are trying to check if the string realConstant is a double, the method checks it but you simply ignore it, here. I believe you have an error because whether it is truly a double or not, the rest of the code will run. In the case where the string is not actually a double, an error will appear since the rest of the code cannot compile.
You should then use an if statement such as:
if (FormatChecker.canParseDouble(realConstant)) {
test = Double.parseDouble(realConstant);
out.println(test);
}
Also, I do not think you should expect an input of "pi" to return a double!

Format method on String

When I am writing this code
float f=56.7876f;
System.out.print(String.format("%32.12f",f));
the output is: 56.787601470947
but, when I am writing this code
System.out.print(String.format("%32.12f",56.7876));
the output is: 56.787600000000
Why in both the cases different outputs are being printed despite of the fact that the functionality of both the code is same?
All floating point numbers without some suffix are double literals in Java. This is the reason why
float ohNoes = 56.7876;
will produce a compiler error (java: incompatible types: possible lossy conversion from double to float).
So If you write
public class Main {
public static void main(String... args) {
System.out.println(String.format("%32.12f",56.7876));
System.out.println(String.format("%32.12f",56.7876f));
}
}
You can see the diference. The first prints the double literal 56.7876, while the second prints the nearest float-representation of 56.7876.
The String.format( format, Object... args) eventually calls :
private void print(float value, Locale l) throws IOException {
print((double) value, l);
}
for float literals. See in Formatter$FormatSpecifier.java in Formatter.java
the value 56.787601470947 that you see is because the float literal 56.7876f is casted to a double as shown in above method.
If you print the following :
float f = 56.7876f;
System.out.println( (double)f );
you will see same value : 56.787601470947
System.out.print(String.format("%32.12f",56.7876)); It is returning 12 char fractional part filling with 0 and it consider 56.7876 as double.
you can refer following link:- https://dzone.com/articles/java-string-format-examples

error while parsing an int from a char in String

import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.

Convert very small double values to string (with scientific notation) (Java)

I'm trying to print a small double number like 6.67e-11, but using Double.toString() returns 0. What can I do to make it print 6.67e-11 (or something similar) instead?
Unable to reproduce:
public class Test {
public static void main(String args[])
{
double d = 6.67e-11;
System.out.println(Double.toString(d)); // Prints "6.67E-11"
}
}
IIRC, Double.toString() always returns a string which allows the exact value to be round-tripped using Double.parseDouble().
My guess is that you don't actually have a small value - that you have 0, due to some rounding errors in other operations.

Using an input string in a textbox

I am trying to have the user input a number, and then that number is used to populate
a text field on a jform. However it keeps giving me errors. If I have the textfield call the str it gives me a numberformatexception, if I have it call the int variable it says it has to be a string...
public static String prePaidstr = "";
public static double prePaidint = 0;
prePaidstr =
JOptionPane.showInputDialog("Enter any amount prepaid:");
prePaidint = Double.parseDouble(prePaidstr);
jTextField13.setText(InvoiceSelectionUI.prePaidstr)
parseDouble converts a String into a Double, which is why it complains if you try to pass it a double.
A NumberFormatException is thrown when parseDouble is unable to successfully turn a String into a double; in this case it's because you're trying to parseDouble on an empty string. prePaidStr needs to contain something like "1.99" - e.g. something that, to a human, looks like a Double.
nm - I fixed it, just had one of the variables switched around

Categories