Here you can find the source of roundDecimals(Float d)
Parameter | Description |
---|---|
d | a parameter |
public static Float roundDecimals(Float d)
//package com.java2s; /*/* www .ja va 2 s . c o m*/ # # Copyright (C) 2010-2011 Anders H??l, Ingenjorsbyn AB # # This program 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. # # This program 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 this program. If not, see <http://www.gnu.org/licenses/>. # */ import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.util.HashMap; import java.util.Locale; import java.util.Map; public class Main { private static Map<String, DecimalFormat> decFormatMapCache = new HashMap<String, DecimalFormat>(); private final static DecimalFormatSymbols DECIMALSEP = new DecimalFormatSymbols(new Locale("us_US")); /** * Round a float to decimal * * @param d * @return rounded to one decimal */ public static Float roundDecimals(Float d) { Float roundedFloat = null; if (d != null) { int nrdec = getNumberOfDecimalPlace(d); StringBuilder strbuf = new StringBuilder(); strbuf.append("#."); for (int i = 0; i < nrdec; i++) { strbuf.append("#"); } DecimalFormat decformatter = decFormatMapCache.get(strbuf.toString()); if (decformatter == null) { decformatter = new DecimalFormat(strbuf.toString(), DECIMALSEP); decFormatMapCache.put(strbuf.toString(), decformatter); } roundedFloat = Float.valueOf(decformatter.format(d)); } return roundedFloat; } private static int getNumberOfDecimalPlace(double value) { final BigDecimal bigDecimal = new BigDecimal("" + value); final String s = bigDecimal.toPlainString(); final int index = s.indexOf('.'); if (index < 0) { return 0; } return s.length() - 1 - index; } }