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

查看:31
本文介绍了使用 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天全站免登陆