Reputation: 365
What is the best/fastest way to convert an exponential integer number of String type (e.g. "2.4490677E7"
) to an integer number String (e.g. "24490677"
) in Java?
Edit: The input is known to always be an integer.
My current proposal is as follows (using org.apache.commons.lang.math.NumberUtils
from Apache Commons):
String input = "2.4490677E7";
String res = null;
Double d = NumberUtils.toDouble(input);
if (d != 0.0d) {
// we have a double number here
res = String.format("%d", d.intValue());
}
Upvotes: 1
Views: 7089
Reputation: 2974
Let me suggest the best approach. It should take care of the precision. If the string is a decimal value the precision after decimal needs to be precised.
String str = "123456789.0111222333444555666777888999E10";
try {
/** DOUBLE **/
double doubleVal = Double.parseDouble(str);//still uses 'E'
System.out.println("Pure Double: "+ doubleVal);// Pure Double: 1.23456789011122227E18
System.out.println(new DecimalFormat("0000000000.00000000000000").format(doubleVal));//1234567890111222270.00000000000000
String plainStrFrmDouble = BigDecimal.valueOf(doubleVal).toPlainString();
System.out.println("From double: " + plainStrFrmDouble);//From double: 1234567890111222270
//convert to desired decimal format
System.out.println(new DecimalFormat("0.0000000").format(Double.parseDouble(plainStrFrmDouble)));//1234567890111222270.0000000
/** BIG DECIMAL **/
String plainStrFrmBigDec = new BigDecimal(str).toPlainString();
System.out.println("From bigdecimal: " + plainStrFrmBigDec); //From bigdecimal: 1234567890111222333.444555666777888999
System.out.println("From bigdecimalNonplain" + new BigDecimal(str));//From bigdecimalNonplain1234567890111222333.444555666777888999 *The most PRECISE way*
} catch (NumberFormatException nfe) {
System.err.println("Error while formatting.");
}
So, I think, new BigDecimal(str) should suffice.
Upvotes: 0
Reputation: 27373
what about
Integer res = ((Double) Double.parseDouble(input)).intValue();
Upvotes: 1
Reputation: 61
hi we can get from this "2.4490677E7" to this "24490677" here is the code
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
String value = "2.4490677E7";
BigDecimal result = new BigDecimal(value);
System.out.println(result.longValue());
}
}
output will be : 24490677
i hope you are looking for this.. Thank you.
Upvotes: 2
Reputation: 6414
If you need precision to be untouched, then you could use BigDecimal to read the string, and then convert it to int value
Upvotes: 2