使用String.format的Java十进制格式? [英] Java decimal formatting using String.format?

查看:69
本文介绍了使用String.format的Java十进制格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个十进制值格式化为一个字符串,在该字符串中,我总是以至少2个小数和最多4个小数显示.

I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4.

例如

"34.49596" would be "34.4959" 
"49.3" would be "49.30"

可以使用String.format命令完成此操作吗?
还是在Java中有更简单/更好的方法来做到这一点.

Can this be done using the String.format command?
Or is there an easier/better way to do this in Java.

推荐答案

您需要java.text.DecimalFormat.

You want java.text.DecimalFormat.

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);

这篇关于使用String.format的Java十进制格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆