AlexDuncan
AlexDuncan

Reputation: 95

Changing the number of integers on a output value after the decimal point

So I'm learning and practicing WP7 application development.

I'm working with integers (currency), and it seems to always display four integers after the decimal place. I'm trying to cut it down to just either ONE or TWO decimal places.

I've been trying to use the "my variable.ToString("C2")" (C for Currency, 2 for number of ints after the decimal)

I'm probably missing something obvious, but please help

enter image description here

Upvotes: 1

Views: 792

Answers (4)

Derek Lakin
Derek Lakin

Reputation: 16319

The "C" format string defines the currency specifier as described on MSDN. This will include the currency symbol for the current culture, or for a specific culture if supplied, e.g.

double amount = 1234.5678;
string formatted = amount.ToString("C", CultureInfo.CreateSpecificCulture("en-US"));
// This gives $1234.56

In your case, it seems that you have a limited set of currency symbols that you support, so I would suggest using the fixed point format specifier "F" instead. By default this will give you 2 decimal points, but you can specify a number to vary this, e.g.

double amount = 1234.5678;
string formatted = amount.ToString("F");
// This gives 1234.56
formatted = amount.ToString("F3");
// This gives 1234.567

Using the fixed point specifier will give you control over the number of decimal points and enable you to concatenate the currency symbol.

Upvotes: 0

sll
sll

Reputation: 62544

decimal number = new decimal(1000.12345678);
string text = number.ToString("#.##");

Output:

1000,12

An other way:

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
decimal val = new decimal(1000.12345678);
string text = val.ToString("c", nfi);

When formatting a currency, NumberFormatInfo allows specifying following properties as well:

  • CurrencyDecimalDigits
  • CurrencyDecimalSeparator
  • CurrencyGroupSeparator
  • CurrencyGroupSizes
  • CurrencyNegativePattern
  • CurrencyPositivePattern
  • CurrencySymbol

See Custom Numeric Format Strings on MSDN for more examples

Upvotes: 1

Alex
Alex

Reputation: 2144

double total = 526.4134
string moneyValue = total.ToString("c");

This will display it in this format: $#.##

Upvotes: 0

Tigran
Tigran

Reputation: 62296

The only thing I would add to "sll" answer is to pay attention on Culture (they often forget to mantion this), like this (example)

string text = val.ToString("#.##", CultureInfo.InvariantCulture);

Upvotes: 0

Related Questions