Hi there,
I’ve ran into a problem recently that I cannot solve for myself. I’ve got a range of numbers from 0 to 1trillion (1,000,000,000,000.00) and I need to format them to always show 3 digits, but at the same time no more than 3.
example:
12.34 --> 12.3
1,234.56 --> 1.23k
2,345.67 --> 2.35k
12,345,678.00 --> 12.3m
123,456,789,012.00 --> 123b
my first attempt was with a simple round()
[php]if ( $isk < 1000 ) {
$isk = number_format ( $isk, 0 );
} elseif ( ( $isk/1000 ) < 1000 ) {
if ( $isk/1000 >= 99 ) {
$isk = round ( ( $isk/1000 ), 0 ) . “k”;
} elseif ( $isk/1000 >= 9 ) {
$isk = round ( ( $isk/1000 ), 1 ) . “k”;
} else {
$isk = round ( ( $isk/1000 ), 2 ) . “k”;
}
} elseif ( ( $isk/1000/1000 ) < 1000 ) {
if ( $isk/1000/1000 >= 99 ) {
$isk = round ( ( $isk/1000/1000 ), 0 ) . “m”;
} elseif ( $isk/1000/1000 >= 9 ) {
$isk = round ( ( $isk/1000/1000 ), 1 ) . “m”;
} else {
$isk = round ( ( $isk/1000/1000 ), 2 ) . “m”;
}
}
[…][/php]
but as you can see that produces a lot of if/else code, which I wanted to avoid, if possible.
I’ve also tried “%.2F” with sprintf() but that doesn’t limit the output to 3 digits, same for number_format().
So I would be very grateful if someone could point me in the right direction to accomplish this task with a bit nicer solution than what I’ve come up with so far.
regards