Search code examples
phpstringdecimalroundingnumber-formatting

How to add commas and round decimals by checking value


I'm building an personal app where I can follow my cryptocurrency coins which I'm currently holding and following. The problem I've noticed are the decimals behind the price. A currency normally has max 2 decimals, but the API of Coinmarketcap gives me more depending on how much the price is.

Below is an example of the value I get from the API, and how I actually want the price to be shown. Values above 1000 will get a comma and no decimals.

$950194.0 -> $950,194
$81851.6 -> $81,852
$4364.97 -> $4,365
$326.024 -> $326.02
$35.0208 -> $35.02
$4.50548 -> $4.51
$0.0547128 -> $0.0547128

I've never tried something ever like this before, so I really don't know how to start. Tried using round() and numberFormat(), but couldn't make the same like how I wanted above in the example.


Solution

  • You can use money_format to make thing easier. However, the problem is about what precision do you want. You have to figure it out yourself since I cannot find the pattern from your examples. Yet I wrote the simple function for you with round and money_format. What the rest is adjust the precision to the point where you want in each case.

    <?php
    
        function my_money_format($number, $precision=0)
        {
            $number = preg_replace( '/[^0-9.,]/', '', $number); // clean the input
            $number = round($number, $precision);
            $format = '%.' . $precision . 'n';
            setlocale(LC_MONETARY, 'en_US'); // set money format to US to use $
            return money_format($format, $number);
        }
    
        echo my_money_format('$950194.0', 0); // $950,194
        echo "\n";
    
        echo my_money_format('$81851.6', 0); // $81,852
        echo "\n";
    
        echo my_money_format('$4364.97', 0); // $4,365
        echo "\n";
    
        echo my_money_format('$326.024', 2); // $326.02
        echo "\n";
    
        echo my_money_format('$35.0208', 2); // $35.02
        echo "\n";
    
        echo my_money_format('$4.50548', 2); // $4.51
        echo "\n";
    
        echo my_money_format('$0.0547128', 7); // $0.0547128
        echo "\n";