Here you can find the source of formatDouble(double d, int precision)
double 10.03 with precision 4 will result in 10.0300
double 2.123456 with precision 4 will result in 2.1234
Parameter | Description |
---|---|
d | a parameter |
precision | a parameter |
public static String formatDouble(double d, int precision)
//package com.java2s; /**/* w w w .ja va2 s . c o m*/ * Stringter: Workbench for string editing * * Copyright (C) 2015 Zdravko Petkov * * 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 3 of the License, or 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/>. */ public class Main { /** * Returns a string of the double with the specified floating point precision * with zeroes added if required to achieve the precision.<br> * * <code>double 10.03 with precision 4 will result in 10.0300</code><br> * <code>double 2.123456 with precision 4 will result in 2.1234</code><br> * * @param d * @param precision * @return */ public static String formatDouble(double d, int precision) { String result = String.valueOf(d); int floatingPoint = result.indexOf('.'); int addZeroes = -(result.length() - (floatingPoint + 1) - precision); if (addZeroes < 0) { return result.substring(0, floatingPoint + 1 + precision); } else { for (int i = 0; i < addZeroes; i++) { result = result + "0"; } return result; } } }