简体   繁体   中英

How to create double value from integer, floating and exponent part in Java?

If I have a structure like this:

public class DoubleData {
    public long integer;
    public int floatingPartOffset; // >=0
    public long floatingPart; // >= 0
    public int exponent;

    public DoubleData(long integer, long floatingPart, int floatingPartOffset, int exponent) 
    {
        this.integer = integer;
        this.floatingPart = floatingPart;
        this.exponent = exponent;
        this.floatingPartOffset = floatingPartOffset
    }
    
    public double toDouble()
}

And I want to implement a behavior like this:

DoubleData(123,567,1,0).toDouble() -> 123.0567

DoubleData(-123,567,0,0).toDouble() -> -123.567

DoubleData(-123,567,2,-8).toDouble() -> -123.00567e-8

How to achieve this? Are there any libraries for that? If it's easier I can replace long and int with byte[] And how to make it as efficient as possible?

That is just math operation using the 3 values

public double toDouble() {
    double floatingPartExponent = Math.pow(10, Math.ceil(Math.log10(floatingPart)));
    double floatSign = Math.signum(integer);
    return (integer + floatSign * floatingPart / floatingPartExponent) * Math.pow(10, exponent);
}

You can concatenate the parts together as a String and convert it to a double with Double.parseDouble .

public double toDouble(){
    return Double.parseDouble(integer + "." + floatingPart + "e" + exponent);
}

They are many ways to do that here is one of them.

import java.math.BigDecimal;
import java.math.MathContext;

public class DoubleData {
     public long integer;
        public long floatingPart; // >= 0
        public int exponent;

        public DoubleData(long integer, long floatingPart, int exponent) {
            this.integer = integer;
            this.floatingPart = floatingPart;
            this.exponent = exponent;
        }
        
        public double toDouble() {
            String stringRepresentation = integer +"."+floatingPart;
            BigDecimal bigDecimal = new BigDecimal(stringRepresentation, new MathContext(exponent));
            return bigDecimal.doubleValue();
        }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM