Java tutorial
//package com.java2s; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; public class Main { /** * Str format. * * @param v * the v * @return the string */ public static String strFormat(String v) { if (v == null) { return "0.00"; } double dv = Double.parseDouble(v); DecimalFormat nf = new DecimalFormat("#.##"); nf.applyPattern("0.00"); return nf.format(dv); } /** * Str format. * * @param v * the v * @return the string */ public static String strFormat(double v) { double sv = round(v, 2); NumberFormat nf = NumberFormat.getInstance(Locale.getDefault()); return nf.format(sv); } /** * Parses the double. * * @param str * the str * @return the double */ public static double parseDouble(String str) { if (str == null) { str = "0"; } return Double.parseDouble(str); } public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } }