java %0d,我如何使java.text.NumberFormat格式0.0d为“0”而不是“+0”?

Need result with sign, except for 0.0d. Ie:

-123.45d -> "-123.45",

123.45d -> "+123.45",

0.0d -> "0".

I invoke format.setPositivePrefix("+") on the instance of DecimalFormat to force the sign in the result for positive inputs.

解决方案

I'm sure there is a more elegant way, but see if this works?

import static org.junit.Assert.assertEquals;

import java.text.ChoiceFormat;

import java.text.DecimalFormat;

import java.text.FieldPosition;

import java.text.NumberFormat;

import java.text.ParsePosition;

import org.junit.Test;

public class NumberFormatTest {

@Test

public void testNumberFormat() {

NumberFormat nf = new MyNumberFormat();

assertEquals("-1234.4", nf.format(-1234.4));

assertEquals("0.0", nf.format(0));

assertEquals("+0.3", nf.format(0.3));

assertEquals("+12.0", nf.format(12));

}

}

class MyNumberFormat extends NumberFormat {

private DecimalFormat df = new DecimalFormat("0.0#");

private ChoiceFormat cf = new ChoiceFormat(new double[] { 0.0,

ChoiceFormat.nextDouble(0.0) }, new String[] { "", "+" });

@Override

public StringBuffer format(double number, StringBuffer toAppendTo,

FieldPosition pos) {

return toAppendTo.append(cf.format(number)).append(df.format(number));

}

@Override

public StringBuffer format(long number, StringBuffer toAppendTo,

FieldPosition pos) {

return toAppendTo.append(cf.format(number)).append(df.format(number));

}

@Override

public Number parse(String source, ParsePosition parsePosition) {

throw new UnsupportedOperationException();

}

}

The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales) is used as the negative subpattern

Hence new DecimalFormat("0.0#") is equivalent to new DecimalFormat("0.0#;-0.0#")

So this would give us: -1234.5 and 1234.5

Now, to add the '+' to positve numbers, I use a ChoiceFormat

0.0 <= X < ChoiceFormat.nextDouble(0.0) will use a choice format of "". ChoiceFormat.nextDouble(0.0) is the smallest number greater than 0.0.

ChoiceFormat.nextDouble(0.0) <= X < 1 will use a choice format of "+".

If there is no match, then either the first or last index is used, depending on whether the number (X) is too low or too high. If the limit array is not in ascending order, the results of formatting will be incorrect. ChoiceFormat also accepts \u221E as equivalent to infinity(INF).

Hence

Double.NEGATIVE_INFINITY <= X < 0 will use "".

1 <= X < Double.POSITIVE_INFINITY will use "+".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值