user6308605
user6308605

Reputation: 731

How to remove decimal in java without removing the remaining digits

Is there any method to remove the . in java into a double value?

Example :

56.11124

to

5611124

Upvotes: 1

Views: 6984

Answers (5)

kewne
kewne

Reputation: 2298

You can convert to BigDecimal and use the unscaledValue method:

BigInteger unscaled = new BigDecimal(myDouble).unscaledValue();

Depending on your intended output, you might also use BigDecimal#valueof(double) to create the intermediate BigDecimal.

Javadoc for BigDecimal#new(double)

Javadoc for BigDecimal#valueOf(double)

Javadoc for BigDecimal#unscaledValue()

Upvotes: 1

jakedipity
jakedipity

Reputation: 900

This might work

class Example {
    public static void main(String[] args) {
        double val = 56.1112;
        while( (double)((int)val) != val )
        {
            val *= 10;
        }

        System.out.printf( "%.0f", val );
    }
}

Output: 561112

This works by casting the double to int which truncates the floating information 56.11124 => 56. While the values aren't equal you multiply it by the base to push the . out. I don't know if this is the best way.

Upvotes: 1

Murat Karagöz
Murat Karagöz

Reputation: 37594

You can convert it to a String and remove the . and convert it back to double something like

double value = 56.11124;
value = Double.valueOf(("" + value).replace(".", "")).doubleValue();

This will return 5611124.0 since its a double you will have the floating point. You can convert it to an int, but you have to take care of the possible overflow. Otherwise it would look like this

int normalized = (int) value;

Upvotes: -1

Sweeper
Sweeper

Reputation: 271300

Here's one way to do it,

First, convert the double to a string. Then, call replace to replace . with an empty string. After that, parse the result into an int:

double d = 5.1;
String doubleString = Double.toString(5.1);
String removedDot = doubleString.replace(".", "");
int result = Integer.parseInt(removedDot);

Obviously, this wouldn't work if the double's string representation is in scientific notation like 5e16. This also does not work on integral double values, like 5, as its string representation is 5.0.

doubles are inaccurate by nature. 5 and 5.0 are the same value. This is why you can't really do this kind of operation. Do you expect different results for a and b?

double a = 5;
double b = 5.0;

If you do, then you can't really do this, since there is no way of knowing what the programmer wrote exactly at runtime.

Upvotes: 1

marstran
marstran

Reputation: 28036

I don't think there's a mathematical way to find out how many decimals there are in a double. You can convert to a String, replace the dot, and then convert it back:

Double.parseDouble(Double.toString(56.11124).replace(".", ""));

Be careful of overflows when you parse the result though!

Upvotes: 5

Related Questions