Java Decimal Format encodeDouble(double d)

Here you can find the source of encodeDouble(double d)

Description

encode Double

License

Apache License

Declaration

public static String encodeDouble(double d) 

Method Source Code


//package com.java2s;
// Licensed under the Apache License, Version 2.0 (the "License");

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Main {
    private static final BigDecimal SIGNIFICAND_COLLATOR = BigDecimal.TEN;
    private static final int EXPONENT_COLLATOR = 999;
    private static final DecimalFormat FULL_DECIMAL_FORMAT = new DecimalFormat();
    private static final DecimalFormat SIGNIFICAND_FORMAT = new DecimalFormat();

    public static String encodeDouble(double d) {
        // todo: replace String manipulation with math
        String decimalString = FULL_DECIMAL_FORMAT.format(d);
        int splitPoint = decimalString.indexOf('E');
        String significand = decimalString.substring(0, splitPoint);
        String exponent = decimalString.substring(splitPoint + 1);
        boolean negativeExponent = exponent.startsWith("-");
        String result;/*from w  ww  . jav a2 s . c om*/

        if (significand.startsWith("-")) {
            // BigDecimal here preserves significand's last digit during add()
            BigDecimal significandValue = new BigDecimal(significand);
            BigDecimal collatedSignificand = significandValue.add(SIGNIFICAND_COLLATOR);
            String formattedSignificand = SIGNIFICAND_FORMAT.format(collatedSignificand);

            if (!negativeExponent) {
                int exponentValue = EXPONENT_COLLATOR - Integer.parseInt(exponent);
                result = "1 " + exponentValue + " " + formattedSignificand;
            } else {
                result = "2 " + exponent.substring(1) + " " + formattedSignificand;
            }
        } else {
            if (d == 0.0D) {
                result = "3 000 0.0000000000000000";
            } else if (negativeExponent) {
                int exponentValue = Integer.parseInt(exponent) + EXPONENT_COLLATOR;
                result = "4 " + exponentValue + " " + significand;
            } else {
                result = "5 " + exponent + " " + significand;
            }
        }
        return result;
    }
}

Related

  1. decimalFormat(String pattern)
  2. decimalFormat(String pattern, double value)
  3. decimalFormatLabel(final long value, final long divider, final String unit)
  4. decimalPointTwo(Float input)
  5. decimalString(double d, boolean forceDigits)
  6. getCorrectionValue(double basicValue, int digit)
  7. getDecimalFormat()
  8. getDecimalFormat()
  9. getDecimalFormat()