Java examples for java.math:BigDecimal
BigDecimal Sets [n] to [dp] decimal places.
/*/*from www. j av a 2 s.co m*/ * BigDecimalHelper.java * Copyright 2003 (C) Jonas Karlsson <jujutsunerd@sf.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Created on April 12, 2003, 3:20 AM */ //package com.java2s; import java.math.BigDecimal; public class Main { public static void main(String[] argv) throws Exception { BigDecimal n = new BigDecimal("1234"); int dp = 2; System.out.println(formatBigDecimal(n, dp)); } /** * Sets [n] to [dp] decimal places. * @param n the BigDecimal to format * @param dp the wanted number of decimal places * @return the formated BigDecimal */ public static BigDecimal formatBigDecimal(BigDecimal n, int dp) { return n.setScale(dp, BigDecimal.ROUND_HALF_UP); // Sets scale and rounds up if most significant (cut off) number >= 5 } }