Formatting positive and negative numbers with C# .NET

Let’s say you have the following three numbers:

  • 13.45
  • -32.56
  • 0

…and you’d like to format them as follows:

  • +13.45
  • -32.56
  • (0)

There’s a special format string that can be used for this purpose. It consists of 3 parts separated by a semi-colon. The first part applies to positive numbers, the second to negative numbers and the third to zeroes:

Read more of this post

Advertisement

Using NumberStyles to parse numbers in C# .NET Part 3

In the previous post we looked at some more values in the NumberStyles enumeration. In this finishing post we’ll look at some more compact enumeration values and how you can pass in your own number format provider for customised and culture-independent solutions.

We’ve seen that you can combine the NumberStyles enumeration values like here:

string rawNumber = "$(14)";
int parsedNumber = int.Parse(rawNumber, NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol);

Read more of this post

Using NumberStyles to parse numbers in C# .NET Part 2

In the previous post we looked at some basic usage of the NumberStyles enumeration. The enumeration allows to parse other representations of numeric values.

Occasionally negative numbers are shown with a trailing negative sign like this: “13-“. There’s a solution for that:

string number = "13-";
int parsed = int.Parse(number, NumberStyles.AllowTrailingSign);

“parsed” will be -13 as expected.

Read more of this post

Using NumberStyles to parse numbers in C# .NET Part 1

There are a lot of number formats out there depending on the industry we’re looking at. E.g. negative numbers can be represented in several different ways:

  • -14
  • (14)
  • 14-
  • 14.00-
  • (14,00)

…and so on. Accounting, finance and other, highly “numeric” fields will have their own standards to represent numbers. Your application may need to parse all these strings and convert them into proper numeric values. The static Parse method of the numeric classes, like int, double, decimal all accept a NumberStyles enumeration. This enumeration is located in the System.Globalization namespace.

Read more of this post

Formatting positive and negative numbers with C# .NET

Let’s say you have the following three numbers:

  • 13.45
  • -32.56
  • 0

…and you’d like to format them as follows:

  • +13.45
  • -32.56
  • (0)

There’s a special format string that can be used for this purpose. It consists of 3 parts separated by a semi-colon. The first part applies to positive numbers, the second to negative numbers and the third to zeroes:

Read more of this post

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: