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 ada开发者_JAVA技巧pt 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
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
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");
}
You will have to write your own function to do this. It isn't built into the default string formatting stuff in .NET.
精彩评论