简体   繁体   中英

In Java, how to print positive signs in the numbers?

Please help me, i have a very simple question here. I would like to know how to print a positive signs in the numbers while using a java code. with C++ i can make it with setiosflags(ios::showpos) and it will print +2,+1,+5,etc.

public static String getStringFromIntWithSign(int num) {
    if (num > 0) { 
        return "+"+num; 
    } else {
        return ""+num;
    }
}

Tweak to suit your needs.

There is no way 1 to tell Java "globally", or for a particular stream, to format numbers with an explicit sign.

There are various ways to format specific numbers with an explicit sign. For example:

    System.out.println("Number is " + (num > 0 ? "+" : "") + num);

The most elegant way is to use the Formatter class and the "+" flag; eg (indirectly)

    System.out.println(String.format("Number is %+d", num));

1 - I should qualify that. In theory you could create and use a funky Locale that delivers a custom NumberFormat object that formats numbers with an explicit sign. That would cause some kinds of i18n message formatting to "globally" change their behavior ... for all cases where the locale is used. But it would probably break other things.

您可以遍历结果并显示 x > 0 等。但我不知道 java 库中的函数仅显示正整数

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM