Java 千分位,精确到指定位的正则实现

2010-05-25 13:39 by hackerzhou

由于现在做的空间要支持默认值,用JSF实现的话得在后台对传入的默认值进行格式化后输出,写了一小段函数(其实是把昨天实现的在前台javascript中格式化的代码移植到java中)。
代码如下:

package main;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
	private static Pattern integerPattern = Pattern.compile("^-?[0-9]*$\r
	private static Pattern thousandsSeparatePattern = Pattern
			.compile("(\\\\d{1,3})(?=(\\\\d{3})+(?:$|\\\\D))\r

	public static void main(String[] args) {
		System.out.println(getFormatNumbers("123456.3", 2, ","));
		System.out.println(getFormatNumbers("2545625.457", 4, ""));
		System.out.println(getFormatNumbers("2545625.457878", 4, ""));
		System.out.println(getFormatNumbers("0.457878", 4, ""));
		System.out.println(getFormatNumbers("57878", 3, ","));
		System.out.println(getFormatNumbers(".57878", 3, ","));
	}

	private static String getFormatNumbers(String value, int decimalPrecision,
			String thousandsSeparator) {
		System.out.print(value+" -> \r
		if (decimalPrecision > 0) {
			if (value == null || value.equals("")) {
				if (!Pattern.matches("^-?[0-9]*\\\\.{0,1}\\\\d{0,"
						+ decimalPrecision + "}$", value)) {
					value = "0";
				}
			}
			String pattern = "0.";
			for (int i = 0; i < decimalPrecision; i++) {
				pattern += "0";
			}
			value = new DecimalFormat(pattern)
					.format(Double.parseDouble(value));
			String integerPart = value.split("\\\\.")[0];
			String decimalPart = value.split("\\\\.")[1];

			Matcher matcher = thousandsSeparatePattern.matcher(integerPart);
			integerPart = matcher.replaceAll("$1" + thousandsSeparator);
			value = integerPart + "." + decimalPart;
		} else {
			if (value == null || value.equals("")) {
				if (!integerPattern.matcher(value).find()) {
					value = "0";
				}
			}
			Matcher matcher = thousandsSeparatePattern.matcher(value);
			value = matcher.replaceAll("$1" + thousandsSeparator);
		}
		return value;
	}
}

运行结果如下:
123456.3 -> 123,456.30
2545625.457 -> 2545625.4570
2545625.457878 -> 2545625.4579
0.457878 -> 0.4579
57878 -> 57,878.000
.57878 -> 0.579

本文基于 署名 2.5 中国大陆 许可协议发布,欢迎转载,演绎或用于商业目的,但是必须保留本文的署名 hackerzhou 并包含 原文链接
本文暂时还没有评论,你可以抢沙发哟。

发表评论