Here you can find the source of truncate(final double v, final int sigNumIndex)
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.. |
public static double truncate(final double v, final int sigNumIndex)
//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)); } }