如何将 C# 中美元和美分分隔的小数转换为字符串值?

发布于 2024-10-04 00:20:12 字数 342 浏览 0 评论 0原文

我需要将十进制货币值显示为字符串,其中美元和美分是分开的,中间有文本。

123.45 => "123 Lt 45 ct"

我提出了以下解决方案:

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

但是,该解决方案有两个缺点:

  1. 在向程序员同事展示该解决方案时,它似乎不直观并且需要一些解释。
  2. 分始终显示为两位数。 (对我来说不是真正的问题,因为目前这就是我需要它的显示方式。)

有没有其他优雅而简单的解决方案?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

誰ツ都不明白 2024-10-11 00:20:12

这是一个相当简单的操作。它应该以一种你的程序员同事能够立即理解的方式完成。你的解决方案非常聪明,但这里不需要聪明。 =)

使用一些冗长的东西,比如

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

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);
若相惜即相离 2024-10-11 00:20:12

我在上面接受的答案中有一些错误(这会让我的结果下降一分钱)

这是我的更正

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

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;
爱殇璃 2024-10-11 00:20:12

这可能有点过头了:

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

十进制二进制表示的格式记录在 这里

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文