Java DecimalFormat returns a "?"
Asked Answered
B

4

9

My DecimalFormat is sometimes returning a '?' when trying to format(). Is there an input that would create this scenario?

For example:

DecimalFormat df = new DecimalFormat("#.####");
df.format(X); // output : '?'

What could X possibly be?

Beniamino answered 7/4, 2011 at 16:0 Comment(4)
What is X, how is it declared, and how defined?Beene
Could you give us a short but complete example which demonstrates the problem?Kusin
My question should've been phrased better, but was looking to answer the generic question "In what cases will a DecimalFormat return a '?' when format()'ingBeniamino
cleaned up my question, thanks guysBeniamino
L
14

It's not a question mark, it's a U+FFFD REPLACEMENT CHARACTER, which is displayed as ? since it can't be mapped to the output encoding:

NaN is formatted as a string, which typically has a single character \uFFFD. This string is determined by the DecimalFormatSymbols object. This is the only value for which the prefixes and suffixes are not used.

Similarly, ? in representation of infinity is a U+221E INFINITY character (∞).

Infinity is formatted as a string, which typically has a single character \u221E, with the positive or negative prefixes and suffixes applied. The infinity string is determined by the DecimalFormatSymbols object.

See also:

Laughter answered 7/4, 2011 at 16:20 Comment(1)
FWIW, Looks like this changed in one of the newer JDKs. I'm now getting "NaN" for NaN instead \uFFFDSignore
D
5

It'll return "?" if X is Float.NaN or Float.POSITIVE_INFINITY. It appears that Float.NEGATIVE_INFINITY returns "-?".

Difficile answered 7/4, 2011 at 16:3 Comment(0)
H
0

I have just solved very similar problem. In my case I was trying to return currency sign to Spring and display it in Thymeleaf template.

public String getAmountDue() {
    DecimalFormat decimalFormat = new DecimalFormat("¤0.00");
    decimalFormat.setCurrency(this.currency);
    String result = decimalFormat.format(amountDue);
    return result;
}

So this was actually returning correctly formatted String but in the browser instead of, e.g. €99.99 I was getting ?99.99 - so instead of currency sign there was question mark displayed.

In the end, that was a problem with my Spring configuration, that I solved by adding characterEncoding to my configuration:

<bean class="org.thymeleaf.spring3.view.ThymeleafViewResolver">
  ...
  <property name="characterEncoding" value="UTF-8" />
</bean>
Henghold answered 4/11, 2014 at 14:47 Comment(0)
C
0

you must have to define local instance over here..like I get Locale.ENGLISH

Double no=20.2563;

    NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern("##.00");

    String output = df.format(no);
Cooking answered 20/5, 2020 at 11:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.