Java Decimal Round truncate(final double v, final int sigNumIndex)

Here you can find the source of truncate(final double v, final int sigNumIndex)

Description

Format the passed in double number by dropping off the less significant numbers so that the least significant number is indicated by the passed in sigNumIndex.

License

Apache License

Parameter

Parameter Description
v the value to be formatted.
sigNumIndex the index for the least significant number. 0 for the 1st digit, 1 for the 10th digit, -1 for the first decimal, etc..

Return

the formatted double with the lesser significant numbers dropped.

Declaration

public static double truncate(final double v, final int sigNumIndex) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.NumberFormat;

public class Main {
    /**//from ww  w .  j  a  v a2s. c o  m
     * Format the passed in double number by dropping off the less significant
     * numbers so that the least significant number is indicated by the passed
     * in sigNumIndex. This function is created because issues in calculation
     * with double numbers, e.g., 3.0 * 0.1 = 0.30000000000000004!
     *
     * @param v
     *            the value to be formatted.
     * @param sigNumIndex
     *            the index for the least significant number. 0 for the 1st
     *            digit, 1 for the 10th digit, -1 for the first decimal, etc..
     * @return the formatted double with the lesser significant numbers dropped.
     */
    public static double truncate(final double v, final int sigNumIndex) {
        // if (sigNumIndex >= 0) {
        // throw new IllegalArgumentException(
        // "Invalid sigNum! Requires negative integer!");
        // }
        if (sigNumIndex >= 0) {
            return ((int) (v / Math.pow(10, sigNumIndex))) * Math.pow(10, sigNumIndex);
        }
        final NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setGroupingUsed(false);
        nf.setMaximumFractionDigits(Math.abs(sigNumIndex));
        return Double.parseDouble(nf.format(v));
    }
}

Related

  1. roundTwoDecimals(double d)
  2. to_decimal(double v)
  3. toLimitDecimalFloatStr(double number, int newScale)
  4. toNumber(Double value, Double defaultValue)
  5. truncate(double d, int digits)