Thonas1601
Thonas1601

Reputation: 1407

How to convert decimal to whole number in java

Hi i have an output as "1.234567E6" and similar. Now i want my output to be converted to 1234567. Could you please suggest how to acheive this? Splitting is one way but then E6 part handling i am not sure.

Also the output will be varying in nature, sometimes it would be 6 decimal places , sometimes 10

Upvotes: 0

Views: 1046

Answers (2)

Eklavya
Eklavya

Reputation: 18420

You can use Double.valueOf then get the long value

long val = Double.valueOf("1.234567E6").longValue();

Or use BigDecimal with longValueExact() to avoid rounding error

long val = new BigDecimal("1.234567E10").longValueExact();

Note: longValueExact() throws Arithmetic Exception if there is any fractional part of this BigDecimal.

You can check the demo here

Upvotes: 1

Cortex
Cortex

Reputation: 684

Use DecimalFormat, it's consistent and clear approach:

DecimalFormat decimalFormat = new DecimalFormat("0");
System.out.println( decimalFormat.format( 1.234567E6 ) );

In String case:

System.out.println( decimalFormat.format( Double.parseDouble("1.234567E6") ) );

Output in both cases

1234567

See code in action: http://tpcg.io/9DsB3GRH

Upvotes: 0

Related Questions