Java 字符串小数转成千分位格式

     java中需要将字符串小数转成千分位格式显示,如下代码,原理是使用正则表达式对整数位进行千分位格式化,然后小数位拼接起来.为什么要这么麻烦的处理,是因为在android程序中使用的NumberFormat,本来是可以做千分位的处理的,但是发现有进位的问题,目前还没找到原因,折中处理.:参考链接:http://www.jb51.net/article/48955.htm

package main;

import java.math.RoundingMode;
import java.text.NumberFormat;

/**
 * 实现将小数类型字符串转成千分位格式的正则表达式
 * 
 * @author Administrator
 *
 */
public class Ceshi {

	public static void main(String[] args) {
		// 06-07 15:38:17.461: I/System.out(25307):
		// 转换前money1.000007343200637E13转换后10,000,073,432,006.40

		System.out.println(returnDouble(1.000007343200637E13));
		String[] strSS = "10000073432006.37".split("\\.");

		String string = strSS[0].replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ",");
		System.out.println(string + "." + strSS[1]);

	}

	// 这个方式在android里面会有10,000,073,432,006.37会进位变成10,000,073,432,006.40,在myeclipse运行是正常的问题,希望大神解决
	public static String returnDouble(double df) {

		NumberFormat numberFormat = NumberFormat.getInstance();

		numberFormat.setRoundingMode(RoundingMode.HALF_UP);
		numberFormat.setMaximumFractionDigits(2);
		numberFormat.setMinimumFractionDigits(2);
		numberFormat.setGroupingUsed(true);
		return numberFormat.format(df);

	}

}

   android中的代码:

//将科学技术法表示的double类型转成千分位显示
	public static String formatMoney(double money, String currency) {
               //注释的这个方式,是有进位问题的,目前还不知道原因
		//		BasicCurrency basicCur = APIDoc.getSystemDocCaptain().getBasicCurrency(currency);
		//
		//		return roundMarginByScale(money, basicCur.getDigit()) + "";
		//		NumberFormat numberFormat = (NumberFormat) moneyFormatHashMap.get(currency);
		//		if (numberFormat == null) {
		//			numberFormat = NumberFormat.getInstance();
		//			BasicCurrency basicCur = APIDoc.getSystemDocCaptain().getBasicCurrency(currency);
		//
		//			if (basicCur == null) {
		//				return "Err";
		//			}
		//			numberFormat.setRoundingMode(RoundingMode.HALF_UP);
		//			numberFormat.setMaximumFractionDigits(basicCur.getDigit());
		//			numberFormat.setMinimumFractionDigits(basicCur.getDigit());
		//			numberFormat.setGroupingUsed(true);//设置为true,可以转成千分位
		//			moneyFormatHashMap.put(currency, numberFormat);
		//		}
		//		synchronized (numberFormat) {
		//			System.out.println("转换前money" + money + "转换后" + numberFormat.format(money));
		//			return numberFormat.format(money);
		//		}

		//DecimalFormat format = new DecimalFormat("#,##0.00");//不以科学计数法显示,并把结果用逗号隔开保留两位小数  
		BigDecimal bigDecimal = new BigDecimal(money);//不以科学计数法显示,正常显示保留两位小数  
		BasicCurrency basicCur = APIDoc.getSystemDocCaptain().getBasicCurrency(currency);

		if (basicCur == null) {
			return "Err";
		}
		return bigDecimal.setScale(basicCur.getDigit(), BigDecimal.ROUND_HALF_UP).toPlainString();
		
		
	}

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:C马雯娟 返回首页