String format问题

漆黑之勺 2013-03-25 02:36:33
我有一个bigDecimal的数,比如
BigDecimal aa = new BigDecimal("1234567.12");
现在需要用String format转换成String类型的 1,234,567.12输出
怎么实现?急,在线等
...全文
173 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
俺是小王子 2013-03-25
  • 打赏
  • 举报
回复
引用 2 楼 blackspoon123 的回复:
引用 1 楼 fangmingshijie 的回复:Java code?12345678910111213141516171819202122232425262728293031323334public static void main(String[] args) { BigDecimal aa = new BigDecimal("1234567.12")……
把二楼的方法改个名字,处理一下BigDecimal的小数点问题不就可以了吗?
dracularking 2013-03-25
  • 打赏
  • 举报
回复
DecimalFormat是专门处理这种需求的

String pattern="###,###.###";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.
  • 打赏
  • 举报
回复
public static void main(String[] args) {
		BigDecimal aa = new BigDecimal("1234567.12");
		System.out.println(String.format("%1$,09.2f", aa));
	}
Inhibitory 2013-03-25
  • 打赏
  • 举报
回复
看MessageFormat的例子,就是为了处理楼主的这种要求的。
漆黑之勺 2013-03-25
  • 打赏
  • 举报
回复
引用 1 楼 fangmingshijie 的回复:
Java code?12345678910111213141516171819202122232425262728293031323334public static void main(String[] args) { BigDecimal aa = new BigDecimal("1234567.12"); System.out.printl……
不能写个方法format,需要类似于String.format("匹配表达式",aa)一行代码搞定
  • 打赏
  • 举报
回复


public static void main(String[] args) {
		BigDecimal aa = new BigDecimal("1234567.12");
		System.out.println(addComma(aa.toString()));
	}
	/**
	* 在数字型字符串千分位加逗号
	* @param str
	* @return
	*/
	public static String addComma(String str){
		boolean neg = false;
		if (str.startsWith("-")){  //处理负数
			str = str.substring(1);
			neg = true;
		}
		String tail = null;
		if (str.indexOf('.') != -1){ //处理小数点
			tail = str.substring(str.indexOf('.'));
			str = str.substring(0, str.indexOf('.'));
		}
		StringBuilder sb = new StringBuilder(str);
		sb.reverse();
		for (int i = 3; i < sb.length(); i += 4){
			sb.insert(i, ',');
		}
		sb.reverse();
		if (neg){
			sb.insert(0, '-');
		}
		if (tail != null){
			sb.append(tail);
		}
		return sb.toString();
	}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧