Java给整数部分的字符串加上千分位分隔符

本来想网上找个例子,结果让人很失望,网上的大部分用的DecimalFormat 、NumberFormat,我随便搞了一个长点的字符串,发现大部分都有小数进度问题。

而且网上的人,都不测试的,写的例子明显不打算在生产上跑,所以还是自己写了一个。

package com.test;

import java.text.ParseException;
import java.util.ArrayList;

public class FormatNumber {
	/**
	 * @Title: addThousandSeparator
	 * @Description: 格式化数字为千分位
	 * @param text
	 * @return 设定文件,由于double的位数有限制,所以这里自己拆分的方式来做。
	 * @return String 返回类型
	 */
	public static String addThousandSeparator(String text) {
		if (text == null) {
			return null;
		}
		int index = text.indexOf(".");
		if (index > 0) {
			String integerPartial = text.substring(0, index);
			String decimalPartial = text.substring(index);
			return addThousandSeparatorForInteger(integerPartial) + decimalPartial;
		} else {
			return addThousandSeparatorForInteger(text);
		}
	}

	// 只给整数加千分位分隔符
	public static String addThousandSeparatorForInteger(String text) {
		int index = text.indexOf(".");
		if (index != -1) {
			return text;
		} else {
			int length = text.length();
			ArrayList<String> stringContainer = new ArrayList<String>();
			while (length > 3) {
				stringContainer.add(text.substring(length - 3, length));
				length = length - 3;
			}
			stringContainer.add(text.substring(0, length)); // 将最前面的小于三个数字的也加入到数组去
			StringBuffer buffer = new StringBuffer();
			for (int i = stringContainer.size() - 1; i >= 0; i--) {
				buffer.append(stringContainer.get(i) + ",");
			}
			buffer.deleteCharAt(buffer.length() - 1);
			return buffer.toString();
		}
	}

	public static void main(String[] args) throws ParseException {
		System.out.println(FormatNumber.addThousandSeparator(".331234567"));
		System.out.println("length:" + "1324678881122.331234567".length());
		System.out.println("index:" + "1324678881122.331234567".indexOf("."));
		System.out.println(FormatNumber.addThousandSeparator("1324678881122.331234567"));
		/**
		 * 结果如下: length:23 index:13 1,324,678,881,122.331234567
		 */

		System.out.println("length:" + "1324678881122.331234567".length());
		System.out.println("index:" + "1324678881122.331234567".indexOf("."));
		System.out.println(FormatNumber.addThousandSeparator("1324678881122"));
		System.out.println(FormatNumber.addThousandSeparator("324678881122"));
		System.out.println(FormatNumber.addThousandSeparator("22"));
		System.out.println(FormatNumber.addThousandSeparator(""));
		System.out.println(FormatNumber.addThousandSeparator(" "));
		System.out.println(FormatNumber.addThousandSeparator(".331234567"));
		System.out.println(FormatNumber.addThousandSeparator("0.331234567"));
		System.out.println(FormatNumber.addThousandSeparator(null));
	}

}

  

posted on 2019-01-03 19:18  坚守梦想  阅读(5709)  评论(0编辑  收藏  举报