How do I convert scientific notation to regular int For example: 1.23E2 I would like to convert it to 123
Thanks.
How do I convert scientific notation to regular int For example: 1.23E2 I would like to convert it to 123
Thanks.
If you have your value as a String, you could use
int val = new BigDecimal(stringValue).intValue();
new BigDecimal(stringValue).intValueExact()
will only return int value if it fits in the range and has no fractional part. Otherwise it will throw ArithmeticException
. Might avoid unexpected truncation/rounding. –
Talley 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
double dlow = Double.parseDouble("-2299999999"); int ilow = (int) dlow; System.out.println("dlow="+String.valueOf(dlow)); System.out.println("(int)dlow="+String.valueOf(ilow)); System.out.println("ilow-dlow="+String.valueOf(ilow-dlow));
dlow=-2.299999999E9 (int)dlow=-2147483648 ilow-dlow=1.52516351E8
–
Murmurous 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.
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 also use something like this.
(int) Double.parseDouble("1.23E2")
You can implement your own solution:
String string = notation.replace(".", "").split("E")[0]
"1.23E4"
you'll get 123 instead of 12300
; or "1.234E1"
will result in 1234
instead of 12
. The string needs to be parsed properly using existing facilities mentioned in other answers for the past 10 years.. –
Krystinakrystle © 2022 - 2024 — McMap. All rights reserved.
float
that is equal to 1.23e2? – Fovea