Thomas Leplus
Thomas Leplus

Reputation: 406

How to prevent minus sign when using DecimalFormat?

I am using a library that lets me configure the way numbers are formatted using a DecimalFormat pattern. I need to remove the minus symbol to show the absolute value of the numbers. I have tried both "0.00###;0.00###" and "0.00###;#" without success. I can choose any minus symbol (e.g. "0.00###;(0.00###)") but I can't have no sign at all?

Thanks in advance for your suggestions,

Tom

Upvotes: 3

Views: 6175

Answers (4)

s3b
s3b

Reputation: 177

If you use "0.00###; 0.00###" (notice the space after the semicolon) the negative sign will not be displayed.

Upvotes: 6

Jonathan Drapeau
Jonathan Drapeau

Reputation: 2610

If you really can't use absolute values with Math.abs as mentionned in other answers, you could change the minus sign in the DecimalFormatSymbols of your DecimalFormat. Beware that you need to set back the value into your DecimalFormatsince it returns a different instance when calling getDecimalFormatSymbols.

You could also use DecimalFormat.setNegativePrefix("") as kdgregory commented.

Upvotes: 4

spheenik
spheenik

Reputation: 2499

It's probably not what you want, but why not use Math.abs() and simply do:

new DecimalFormat("0.00###").format(Math.abs(value))

Upvotes: 1

Dan O
Dan O

Reputation: 6090

why can't you call Math.abs() before formatting your number?

int myNum = -123;
myNum = Math.abs(myNum);
System.out.println(myNum); // 123

Upvotes: 7

Related Questions