开发者

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

开发者 https://www.devze.com 2023-01-27 02:33 出处:网络
I need to display decimal money value as string, where dollars and cents are separate with text in between.

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 tw开发者_如何学Co 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?


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);


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;


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号