Java: Convert scientific notation to regular int

I am assuming you have it as a string.

Take a look at the DecimalFormat class. Most people use it for formatting numbers as strings, but it actually has a parse method to go the other way around! You initialize it with your pattern (see the tutorial), and then invoke parse() on the input string.


If you have your value as a String, you could use

int val = new BigDecimal(stringValue).intValue();

Check out DecimalFormat.parse().

Sample code:

DecimalFormat df = new DecimalFormat();
Number num = df.parse("1.23E2", new ParsePosition(0));
int ans = num.intValue();
System.out.println(ans); // This prints 123

You can just cast it to int as:

double d = 1.23E2; // or float d = 1.23E2f;
int i = (int)d; // i is now 123

Tags:

Java