Welcome, guest | Sign In | My Account | Store | Cart

Dollarfy Function those the following things to a floating point number:

  1. This function inserts a comma separator into every 3 digits. For example: 100000.1252 will be 100,000.1252.

  2. Round to the decimal number to the next significant figure. For example: 100,000.1252 will be 100,000.13

  3. Add a dollar sign to the number. For example: 100,000.13 will be $100,000.13

Syntax: dollarfy (Decimal Number, Decimal places);

Example: dollarfy (100000.1252, 2);

Output will be: $100,000.13 (Rounded to the second Decimal place)

Note: You will need the commify function for it to work. dollarfy() function needs the commify() function to work.

PHP, 40 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php

## Passing values to the dollarfy() function
$Price = dollarfy (100000.1252, 2);

## Display output
print "output: $Price" . "<br>";

## Dollarfy Function
function dollarfy ($num,$dec) {
	 
	$format="%.$dec" . "f";  
        $number=sprintf($format,$num);
        $str=strtok($number,".");
        $dc=strtok(".");      
        $str=commify($str);
        $return="\$&nbsp;$str";

        if ($dec!=0) { 
                $return = "$return" . ".$dc";
        } 
        return($return); 
}

## Commify Function
function commify ($str) { 
        $n = strlen($str); 
        if ($n <= 3) { 
                $return=$str;
        } 
        else { 
                $pre=substr($str,0,$n-3); 
                $post=substr($str,$n-3,3); 
                $pre=commify($pre); 
                $return="$pre,$post"; 
        }
        return($return); 
}

?> 

This function can be used for financial, real estate, or any online reporting system where you want to make numbers more legible to the user.

Check out my Commify function lacted here: http://aspn.activestate.com/ASPN/Cookbook/PHP/Recipe/202051

Courtesy of Alvin Estevez, Enigma Software Group, Inc. http://www.enigmasoftwaregroup.com

2 comments

Andrew Hanna 19 years, 5 months ago  # | flag

Reiventing the Wheel. Instead of reiventing the wheel, you could just use the number_format() function builtin to PHP since version 3:

http://ca.php.net/number_format

-Andrew

Michal Kočárek 15 years, 5 months ago  # | flag

...or money_format(), http://ca.php.net/manual/en/function.money-format.php and you don't even need to add the dollar by yourself.

Created by Alvin Estevez on Sat, 24 May 2003 (MIT)
PHP recipes (51)
Alvin Estevez's recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks