问题
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
回答1:
If you use "0.00###; 0.00###" (notice the space after the semicolon) the negative sign will not be displayed.
回答2:
why can't you call Math.abs() before formatting your number?
int myNum = -123;
myNum = Math.abs(myNum);
System.out.println(myNum); // 123
回答3:
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.
回答4:
It's probably not what you want, but why not use Math.abs() and simply do:
new DecimalFormat("0.00###").format(Math.abs(value))
来源:https://stackoverflow.com/questions/24021475/how-to-prevent-minus-sign-when-using-decimalformat