Reputation: 1468
I would like to know the simplest way to transform a number to a truncated and rounded form.
I know many way to do it "manually" (truncate manually, put a comma then round the number after) but I think there are easier ways to do it (probably with Maths methods).
Example :
1 234 567 should become 1,2 M
1 567 890 should become 1.6 M
Upvotes: 0
Views: 79
Reputation:
The integer part of the base-10 logarithm gives you the exponent as appearing in the scientific notation.
If you want s
significant digits, normalize by dividing by ten to the exponent, rescale by ten to s-1
and round.
e= floor(log10(x)); // => e = 6
x= Round(x * pow(10, s - 1 - e)); // => x = 12, x = 16
Upvotes: 1
Reputation: 3914
Something like that:
static string FormatNumber(uint n)
{
if (n < 1000)
return n.ToString();
if (n < 10000)
return String.Format("{0:#,.##}K", n - 5);
if (n < 100000)
return String.Format("{0:#,.#}K", n - 50);
if (n < 1000000)
return String.Format("{0:#,.}K", n - 500);
if (n < 10000000)
return String.Format("{0:#,,.##}M", n - 5000);
if (n < 100000000)
return String.Format("{0:#,,.#}M", n - 50000);
if (n < 1000000000)
return String.Format("{0:#,,.}M", n - 500000);
return String.Format("{0:#,,,.##}B", n - 5000000);
}
Will give you this output:
1249 1.24K
12499 12.4K
124999 124K
1249999 1.24M
12499999 12.4M
124999999 124M
1249999999 1.24B
I don't think there are built-in libraries to do this.
Upvotes: 1