Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
I have the following decimal number which i have shown below. Please help me to convert this decimal values to the format i have shown below:

double val = 2186382.34;
double val1 = 186382.34;
double val2 = 86382.34;
double val3 = 6382.34;
double val4 = 382.34;


I need in this format:

val = $2,186k;
val1 = $186k;
val2 = $86k;
val3 = $6k;
val4 = $382;
Posted

C#
string ConvertNumber(decimal num) {
    if (num >= 100000)
        return "$" + ConvertNumber(num / 10000) + "K";
    if (num >= 10000) {
        return "$" + (num / 1000).ToString("0.#") + "K";
    }
    return num.ToString("#,0");
}

This should do :)

[Update - Testing]
ConvertNumber(11111) returns $11.1K
ConvertNumber(1111111) returns $111K

-KR
 
Share this answer
 
v2
Comments
[no name] 6-Nov-15 8:37am    
Thank you :)
Krunal Rohit 6-Nov-15 8:38am    
Glad I could help. :)

-KR
Richard Deeming 6-Nov-15 9:44am    
You don't need the first if block - it's a recursive call that won't work properly for very large numbers.
BillWoodruff 6-Nov-15 11:45am    
+5 The use of recursion in a simple problem like this always leaves me a little queasy, but your solution works. One suggestion: use the 'decimal suffix 'm or 'M after internal decimal numbers in the code; this is not required, but I think contributes to code maintenance, and may remind the user to make sure their input value when they call the method is in decimal format.
Krunal Rohit 6-Nov-15 12:00pm    
Yes, I didn't test it but after reading your comment, I did. I updated the solution :)


-KR
Here's a simple approach that will handle negative numbers, and give you the correct suffix for thousands, millions and billions:
C#
public static string Convert(double value)
{
    double absValue = Math.Abs(value);
    if (absValue >= 1000000000)
    {
        return string.Format("${0:F2}b", value / 1000000000);
    }
    if (absValue >= 1000000)
    {
        return string.Format("${0:F2}m", value / 1000000);
    }
    if (absValue >= 1000)
    {
        return string.Format("${0:F1}k", value / 1000);
    }

    return string.Format("${0:F0}", value);
}

If you need different numbers of decimal places for the different suffixes, adjust the number after the F in the format string, or use your own custom format string.

If you want a different set of suffixes, add or remove if blocks. Just make sure you test the values in descending order. :)
 
Share this answer
 
Comments
Maciej Los 6-Nov-15 15:01pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900