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

I need to display a decimal monetary value as a string, where the dollars and cents will be separate with the text between them.

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:

  • By showing this solution to another programmer, it seems unintuitive and requires an explanation.
  • Cents are always displayed as two digits. (Not a real problem for me, as this is currently the way I need it to display.)

Is there an alternative elegant and simple solution?

+3
source share
3 answers

( )

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

. , - . , . =)

- ,

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

It could be a little on 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 decimal binary format is documented here .

0
source

Source: https://habr.com/ru/post/1776863/


All Articles