字串取小數幾位,不足碼補零
package com.yslifes.util; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; public class NumberUtils { /** * 字串取小數幾位 * * @param str * 字串(數字) * @param precision * 小數幾碼 * @return 取好的字串 */ public static String MarkUpZero(String str, int precision) { String maskup = "00000000000"; String retVal = str; retVal = StringUtils.nvl(retVal, "0"); if (precision == 0) { int idx = retVal.indexOf("."); if (idx == -1) return retVal; else return retVal.substring(0, idx); } if (precision > 0 && retVal.indexOf(".") == -1) { retVal += "."; } int len = retVal.indexOf("."); return (retVal + maskup).substring(0, retVal.indexOf(".")) + (retVal + maskup).substring(retVal.indexOf("."), len + precision + 1); } public static void main(String args[]) { System.out.println("22222取小數二位:\t\t\t"+MarkUpZero("22222", 2)); System.out.println("22222.1取小數二位:\t\t"+MarkUpZero("22222.1", 2)); System.out.println("22222.11111取小數二位:\t\t"+MarkUpZero("22222.11111", 2)); System.out.println("22222.1取小數零位:\t\t"+MarkUpZero("22222.1", 0)); } }Read More