简体   繁体   English

C# 仅在没有美分时使用 String.Format 删除货币中的小数

[英]C# Remove Decimal in Currency Only If No Cents using String.Format

How do I most efficiently remove decimals in a currency using String.Format only if the variable does not contain cents?当变量不包含美分时,如何使用 String.Format 最有效地删除货币中的小数?

  • So if Price is 200000, it should output: $200,000所以如果价格是 200000,它应该输出:$200,000
  • So if Price is 200000.00, it should output: $200,000所以如果价格是 200000.00,它应该输出:$200,000
  • If Price is 200000.10, it should output: $200,000.10如果价格是 200000.10,它应该输出:$200,000.10
  • If Price is 300.3, it should output: $300.30如果价格是 300.3,它应该输出:$300.30
  • If Price is 20, it should output $20如果价格是 20,它应该输出 20 美元
  • If Price is .2, it should output $0.20如果价格是 0.2,它应该输出 0.20 美元

etc...等等...

I currently have:我目前有:

$"{String.Format("{0:C}", Price)}"

Thank you.谢谢你。

您应该能够通过使用基于值 mod 1 是否等于零的不同格式来做到这一点

Price.ToString(Price % 1 == 0 ? "C0" : "C");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM