Reputation: 1691
I am performing subtraction operation in my code, and convert the received result to string. The result could be grater than 0 or negative. In case of negative result the '-' is automatically added to the result string.
I need to add the '+' sign, If i received possitive result. Please, advise me the most simple way to do that.
My code:
return String.valueOf(settlingScoreMap.get(market.getSettlingScore()).getAway()
- settlingScoreMap.get(market.getSettlingScore()).getHome());
Upvotes: 1
Views: 204
Reputation: 4948
public static void main(String[] args) {
int val1 = 5;
int val2 = 4;
int result = val1 - val2;
System.out.println(result > 0 ? "+" + result : String.valueOf(result));
}
Upvotes: 0
Reputation: 59
int x=5;
int y=3;
int result=x-y;
if (result<=0)
System.out.println(String.valueOf(result));
else
System.out.println("+"+String.valueOf(result));
Upvotes: 1
Reputation: 140318
Use String.format
:
String.format("%+d", theIntValueToPrint)
^ This indicates that the sign should be added.
Upvotes: 12