如何将 C# 中美元和美分分隔的小数转换为字符串值?
我需要将十进制货币值显示为字符串,其中美元和美分是分开的,中间有文本。
123.45 => "123 Lt 45 ct"
我提出了以下解决方案:
(value*100).ToString("#0 Lt 00 ct");
但是,该解决方案有两个缺点:
- 在向程序员同事展示该解决方案时,它似乎不直观并且需要一些解释。
- 分始终显示为两位数。 (对我来说不是真正的问题,因为目前这就是我需要它的显示方式。)
有没有其他优雅而简单的解决方案?
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:
- Upon showing this solution to a fellow programmer, it appears to be unintuitive and requires some explaining.
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个相当简单的操作。它应该以一种你的程序员同事能够立即理解的方式完成。你的解决方案非常聪明,但这里不需要聪明。 =)
使用一些冗长的东西,比如
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
我在上面接受的答案中有一些错误(这会让我的结果下降一分钱)
这是我的更正
I had some errors with accepted answer above (it would drop my result one penny)
Here is my correction
这可能有点过头了:
十进制二进制表示的格式记录在 这里。
This might be a bit over the top:
The format of the decimal binary representation is documented here.