Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format number with + and - sign

I have some WPF textblocks in a stackpanel that I want to databind and format.

E.g. the following formats a date 24h style without the seconds part:

<TextBlock Text="{Binding MyCustomObject, StringFormat={}{0:HH:mm}}" />

Now, I would like to bind an integer and also display the + and - sign (i.e. +6 or -4).

<TextBlock Text="{Binding MyOtherCustomObject, StringFormat={}{0:+#}}" />

This however, does not work. Is this possible or do I have to write a complete converter just for this?

EDIT

Nikolays post led me to the answer:

<TextBlock Text="{Binding MyOtherCustomObject, StringFormat={}{0:+#;-#;''}}" />

In essence you provide a format for positive numbers, negative numbers and an optional part what to do with zero. In this case I stated that a zero should be displayed as an empty string.

Regards,

Michel

like image 305
Michel van Engelen Avatar asked Mar 20 '12 06:03

Michel van Engelen


People also ask

How do you write numbers in format?

Overview of number formatting Numbers with two or more digits should be written as numerals unless they are at the start of a sentence (see examples). Numbers between 1000 and 9999 should contain no punctuation. Numbers with five or more digits should include commas (not decimal points or full stops).

What is standard numeric format?

Numeric format specifier (N) The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd. ddd…", where "-" indicates a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." indicates a decimal point symbol.


1 Answers

Try this:

<TextBlock Text="{Binding MyOtherCustomObject, StringFormat={}{0:+#;-#;''}}" />

This article has nice samples of int formatting - http://www.csharp-examples.net/string-format-int/

like image 199
Nikolay Avatar answered Oct 04 '22 01:10

Nikolay