Reputation: 516
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:
Is there any alternative elegant and simple solution?
Upvotes: 4
Views: 8592
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
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
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