Java examples for java.math:BigDecimal
returns amount as a percentage of total.
/*/*from w w w. j a v a 2s . c om*/ Anders H?fft, note: This class was downloaded as a quick, and temprory, way of getting a BigDecimal ln() method. The code belongs to Cyclos. See comment below: This file is part of Cyclos (www.cyclos.org). A project of the Social Trade Organisation (www.socialtrade.org). Cyclos is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Cyclos 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 General Public License for more details. You should have received a copy of the GNU General Public License along with Cyclos; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ //package com.java2s; import java.math.BigDecimal; import java.math.MathContext; public class Main { public static void main(String[] argv) throws Exception { BigDecimal amount = new BigDecimal("1234"); BigDecimal total = new BigDecimal("1234"); System.out.println(asPercentageOf(amount, total)); } private static final int MAX_PRECISION = 10; public static final BigDecimal ONE_HUNDRED = new BigDecimal(100.0); /** * returns amount as a percentage of total. Example: if amount is 5 and total is 50, then BigDecimalHelper.asPercentageOf(amount, total) equals 10 * (%). * @param amount the BigDecimal to be written as a percentage. * @param total the BigDecimal representing the total amount of which amount is a percentage. * @return amount as a BigDecimal percentage of total. */ public static BigDecimal asPercentageOf(final BigDecimal amount, final BigDecimal total) { final MathContext mathContext = new MathContext(MAX_PRECISION); final BigDecimal asFractionOf = amount.divide(total, mathContext); return asFractionOf.multiply(ONE_HUNDRED, mathContext); } }