简体   繁体   English

C#中的货币格式缩短输出字符串

[英]Currency Format in C# to shorten the output string

Hey, I currently have a Currency Format method: 嘿,我目前有一种货币格式方法:

private string FormatCurrency(double moneyIn)
{
    CultureInfo ci = new CultureInfo("en-GB");

    return moneyIn.ToString("c", ci);
}

I'm looking to adapt this to shorten the string as the currency get's larger. 我正在寻求调整这个以缩短字符串,因为货币变得更大。 Kind of like how stack overflow goes from 999 to 1k instead of 1000 (or 1.6k instead of 1555). 有点像堆栈溢出从999到1k而不是1000(或1.6k而不是1555)。

I imagine that this is a relativly easy task however is there any built in function for it or would you just have to manually manipulate the string? 我想这是一个相对容易的任务,但有没有内置的功能,或者你只需​​要手动操作字符串?

Thanks 谢谢

I would use the following to accomplish what you require, I don't think there is anything builtin to do this directly! 我将使用以下内容来完成您的需求,我认为没有任何内置可以直接执行此操作!

return (moneyIn > 999) ? (moneyIn/(double)1000).ToString("c", ci) + "k" : moneyIn.ToString("c", ci);

You may also want to round the result of moneyIn/1000 to 1 decmial place. 您可能还想将moneyIn / 1000的结果舍入到1个decmial位置。

HTH HTH

There is nothing built in to the framework. 框架内置了任何内容。 You will have to implement your own logic for this. 您必须为此实现自己的逻辑。

This question comes up fairly often - see the answers to this question (Format Number like StackoverFlow (rounded to thousands with K suffix)). 这个问题经常出现 - 请参阅问题的答案(格式编号,如StackoverFlow(四舍五入为K后缀))。

// Taken from the linked question. Thanks to SLaks
static string FormatNumber(int num) {
  if (num >= 100000)
    return FormatNumber(num / 1000) + "K";
  if (num >= 10000) {
    return (num / 1000D).ToString("0.#") + "K";
  }
  return num.ToString("#,0");
}

You will have to write your own function to do this. 您必须编写自己的函数才能执行此操作。 It isn't built into the default string formatting stuff in .NET. 它没有内置到.NET中的默认字符串格式化内容中。

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

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