Domas
Domas

Reputation: 516

How to convert decimal to string value for dollars and cents separated in C#?

I need to display decimal money value as string, where dollars and cents are separate with text in between.

123.45 => "123 Lt 45 ct"

I came up with the following solution:

(value*100).ToString("#0 Lt 00 ct");

However, this solution has two drawbacks:

  1. Upon showing this solution to a fellow programmer, it appears to be unintuitive and requires some explaining.
  2. Cents are allways displayed as two digits. (Not real problem for me, as currently this is how I need it to be displayed.)

Is there any alternative elegant and simple solution?

Upvotes: 4

Views: 8592

Answers (3)

Matthew Bierman
Matthew Bierman

Reputation: 360

I had some errors with accepted answer above (it would drop my result one penny)

Here is my correction

 double val = 125.79;
 double roundedVal = Math.Round(val, 2);
 double dollars = Math.Floor(roundedVal);
 double cents = Math.Round((roundedVal - dollars), 2) * 100;

Upvotes: 0

VVS
VVS

Reputation: 19604

This might be a bit over the top:

decimal value = 123.45M;

int precision = (Decimal.GetBits(value)[3] & 0x00FF0000) >> 16;
decimal integral = Math.Truncate(value);
decimal fraction = Math.Truncate((decimal)Math.Pow(10, precision) * (value - integral));

Console.WriteLine(string.Format("{0} Lt {1} ct", integral, fraction));

The format of the decimal binary representation is documented here.

Upvotes: 0

Jens
Jens

Reputation: 25563

This is a fairly simple operation. It should be done in a way, that your fellow programmers understand instantly. Your solution is quite clever, but cleverness is not needed here. =)

Use something verbose like

double value = 123.45;
int dollars = (int)value;
int cents = (int)((value - dollars) * 100);
String result = String.Format("{0:#0} Lt {1:00} ct", dollars, cents);

Upvotes: 8

Related Questions