Java中的条件数字格式 [英] Conditional Number Formatting In Java

查看:248
本文介绍了Java中的条件数字格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中格式化浮点数,以便浮动组件仅在不为零时显示?例如:

How can I format Floats in Java so that the float component is displayed only if it's not zero? For example:


123.45 -> 123.45
99.0   -> 99
23.2   -> 23.2
45.0   -> 45

编辑:我忘了提 - 我还在Java 1.4上 - 对不起!

I forgot to mention - I'm still on Java 1.4 - sorry!

推荐答案

如果使用 DecimalFormat 并在模式中指定#,如果它不为零,则仅显示该值。

If you use DecimalFormat and specify # in the pattern it only displays the value if it is not zero.

查看我的问题如何格式化java中的数字?

示例代码

 DecimalFormat format = new DecimalFormat("###.##");

    double[] doubles = {123.45, 99.0, 23.2, 45.0};
    for(int i=0;i<doubles.length;i++){
        System.out.println(format.format(doubles[i]));
    }

这篇关于Java中的条件数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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