Print Currency Number Format in PHP

后端 未结 7 791
野性不改
野性不改 2020-11-30 00:28

I have some price values to display in my page.

I am writing a function which takes the float price and returns the formatted currency val with currency code too..

相关标签:
7条回答
  • 2020-11-30 01:10

    I built this little function to automatically format anything into a nice currency format.

    function formatDollars($dollars)
    {
        return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
    }
    

    Edit

    It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:

    function formatDollars($dollars)
    {
        $formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
        return $dollars < 0 ? "({$formatted})" : "{$formatted}";
    }
    
    0 讨论(0)
提交回复
热议问题