"+123.45", 0.0d -> “0”。 我调用 format.setPositi-6ren">
gpt4 book ai didi

java - 如何将 java.text.NumberFormat 格式 0.0d 设为 “0” 而不是 “+0” ?

转载 作者:行者123 更新时间:2023-12-04 07:08:53 26 4
gpt4 key购买 nike

需要带符号的结果,0.0d 除外。 IE:

-123.45d -> "-123.45",
123.45d -> "+123.45",
0.0d -> “0”。

我调用 format.setPositivePrefix("+")在 DecimalFormat 的实例上强制在结果中为正输入符号。

最佳答案

我确定有更优雅的方式,但看看这是否有效?

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();
}
}

根据 DecimalFormat

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



因此 new DecimalFormat("0.0#")相当于 new DecimalFormat("0.0#;-0.0#")
所以这会给我们: -1234.51234.5
现在,要将“+”添加到正数,我使用 ChoiceFormat
  • 0.0 <= X < ChoiceFormat.nextDouble(0.0)将使用 "" 的选择格式. ChoiceFormat.nextDouble(0.0)是大于 0.0 的最小数.
  • ChoiceFormat.nextDouble(0.0) <= X < 1将使用 "+" 的选择格式.

  • 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).



    因此
  • Double.NEGATIVE_INFINITY <= X < 0将使用 "" .
  • 1 <= X < Double.POSITIVE_INFINITY将使用 "+" .
  • 关于java - 如何将 java.text.NumberFormat 格式 0.0d 设为 “0” 而不是 “+0” ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/673841/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com