Java Long to longToNumberWithDecimalPlaces(long longValue, int decimalPlaces)

Here you can find the source of longToNumberWithDecimalPlaces(long longValue, int decimalPlaces)

Description

converts a long into representation like double.
If longValue 12345 and decimalPlaces = 2 output is 123.45
if long value = 12 and decimalPlaces =3 output is 0.012

License

Open Source License

Parameter

Parameter Description
longValue a parameter
decimalPlaces a parameter

Declaration

public static char[] longToNumberWithDecimalPlaces(long longValue, int decimalPlaces) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from w w w .j  a v a2 s. com
     * converts a long into representation like double.<br/>
     * If longValue 12345 and decimalPlaces = 2 output is 123.45<br/>
     * if long value = 12 and decimalPlaces =3 output is 0.012<br/>
     * 
     * @param longValue
     * @param decimalPlaces
     * @return
     */
    public static char[] longToNumberWithDecimalPlaces(long longValue, int decimalPlaces) {
        String value = Long.toString(longValue);
        char[] charVal;
        int pointPos = value.length() - decimalPlaces;

        int copyStart = 0;
        if (value.charAt(0) == '-') {
            copyStart = 1;
        }

        // we need padding because final |value| < 1
        if (pointPos < 1 || (pointPos < 2 && copyStart == 1)) {
            int pos = 0;

            // this makes: a aditional leading 0 + a point + padding
            charVal = new char[value.length() - (pointPos - copyStart) + 2];
            // ..and a heading -
            if (copyStart == 1) {
                charVal[pos++] = '-';
            }

            charVal[pos++] = '0';
            charVal[pos++] = '.';

            // do padding behind 0.
            for (int i = 0; i < -(pointPos - copyStart); i++) {
                charVal[pos++] = '0';
            }
            // copy value
            value.getChars(copyStart, value.length(), charVal, pos);

        } else {

            // plus one additional point
            charVal = new char[value.length() + 1];

            // copy value & insert point
            value.getChars(0, pointPos, charVal, 0);
            charVal[pointPos] = '.';
            value.getChars(pointPos, value.length(), charVal, pointPos + 1);

        }
        return charVal;
    }
}

Related

  1. longToN62(long l)
  2. longToName(long l)
  3. longToNBuf(long l, char[] chars)
  4. longToNetworkByteOrderArray(long addr)
  5. longToNetworkBytes(long value)
  6. LongToOctString(final long value)
  7. longToOther(Object val, Class dest)
  8. longToPrefixCoded(final long val, final int shift, final char[] buffer)
  9. longToRegisters(long v)