Here you can find the source of formatToString(double num, int decPlaces)
Parameter | Description |
---|---|
num | the number to format |
decPlaces | the number of places to display |
public static String formatToString(double num, int decPlaces)
//package com.java2s; /*/*from w w w .j a v a2s .c o m*/ * Copyright 1998-2007 The Brookings Institution, NuTech Solutions,Inc., Metascape LLC, and contributors. * All rights reserved. * This program and the accompanying materials are made available solely under the BSD license "ascape-license.txt". * Any referenced or included libraries carry licenses of their respective copyright holders. */ import java.text.DecimalFormat; import java.text.NumberFormat; public class Main { /** * Returns the supplied number formatted as a string with the given number of decimal places fixed * and padded with zeroes if needed. * For example, <code>formatToString(23.436765, 2) would return "23.44". * @param num the number to format * @param decPlaces the number of places to display */ public static String formatToString(double num, int decPlaces) { NumberFormat nf = NumberFormat.getNumberInstance(); if (Math.abs(num) >= 1.0E9) { // generate scientific notation try { // we use "try" because the number format of some locales may not support scientific notation ((DecimalFormat) nf).applyPattern("0.###E0"); } catch (Exception e) { } } nf.setGroupingUsed(false); nf.setMinimumFractionDigits(decPlaces); nf.setMaximumFractionDigits(decPlaces); return nf.format(num); } }