在java中为零的负号 [英] Negative sign in case of zero in java

查看:365
本文介绍了在java中为零的负号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当结果返回零时,是否有任何方法可以截断负号;使用十进制格式时?

Is there any way to truncate the negative sign when the result returns zero; while using decimal format?

DecimalFormat df = new DecimalFormat("#,##0.0");
df.setRoundingMode(RoundingMode.HALF_UP);
formattedValue = df.format("-0.023");

上面的代码返回-0.0。有没有办法只返回0.0?但是,当结果为负数时,我想保留负号。

The above code returns -0.0 . Is there any way by which it will return only 0.0? However, I want to retain the negative sign when the result is a negative number.

推荐答案

我认为没有办法只使用 DecimalFormat 进行此操作,但是这个单线程可以解决问题:

I don't think there's a way of doing it just with DecimalFormat, but this one-liner takes care of the problem:

formattedValue = formattedValue.replaceAll( "^-(?=0(.0*)?$)", "");

它删除(替换为)减号,如果后跟0-n字符0.00000 ...,那么这将适用于任何类似的结果,例如 - 0 - 0。 - 0.000000000

It removes (replaces with "") the minus sign if it's followed by 0-n characters of "0.00000...", so this will work for any similar result such as "-0", "-0." or "-0.000000000"

以下是一些测试代码:

public static void main(String[] args) {
    System.out.println(format(-0.023));
    System.out.println(format(12.123));
    System.out.println(format(-12.345));
    System.out.println(format(-0.123));
    System.out.println(format(-1.777));
}

public static String format(double number) {
    DecimalFormat df = new DecimalFormat("#,##0.0");
    df.setRoundingMode(RoundingMode.HALF_UP);
    String formattedValue = df.format(number);
    formattedValue = formattedValue.replaceAll("^-(?=0(.0*)?$)", "");
    return formattedValue;
}

输出(按预期):

0.0
12.1
-12.3
-0.1
-1.8

这篇关于在java中为零的负号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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