Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 914
Domas Avatar asked Nov 02 '25 03:11

Domas


1 Answers

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);
like image 69
Jens Avatar answered Nov 04 '25 18:11

Jens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!