Currency Format in C# to shorten the output string

喜你入骨 提交于 2019-12-23 03:14:48

问题


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

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


回答1:


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.

HTH




回答2:


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

// 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");
}



回答3:


You will have to write your own function to do this. It isn't built into the default string formatting stuff in .NET.



来源:https://stackoverflow.com/questions/2690385/currency-format-in-c-sharp-to-shorten-the-output-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!