0

Function not working for prefix with 8[any numbers].

input: 970 output:$9.70
input: 870 output:$870
input: 800 output:$800

function toMoney( $val, $symbol = '$', $r = 2 ) {
    $n = $val; 
    $c = is_float($n) ? 1 : number_format( $n , $r );
    $d = '.';
    $t = ',';
    $sign = ( $n < 0 ) ? '-' : '';
    $i = $n = number_format( abs( $n ), $r ); 
    $j = ( ( $j = $i.length ) > 3 ) ? $j % 3 : 0; 

   return  $symbol.$sign .( $j ? substr( $i, 0, $j) + $t : '').preg_replace('/(\d{3})(?=\d)/',"$1" + $t,substr($i,$j)) ;
}

Function taken from: Money conversion not worked

The above error rectified in the below

  function toMoney( $val, $symbol = '$', $r = 2 ) {
        $n = $val; 
        $c = is_float($n) ? 1 : number_format( $n , $r );
        $d = '.';
        $t = ',';
        $sign = ( $n < 0 ) ? '-' : '';
        $i = $n = number_format( abs( $n ), $r ); 
        $j = ( ( $j = strlen($i) ) > 3 ) ? $j % 3 : 0; 

       return  $symbol.$sign .( $j ? substr( $i, 0, $j) + $t : '').preg_replace('/(\d{3})(?=\d)/',"$1" + $t,substr($i,$j)) ;
    }
Community
  • 1
  • 1
Bharanikumar
  • 25,457
  • 50
  • 131
  • 201

2 Answers2

1

If I understand well, you want the two last numbers to be cents?

so why don't just do :

$val = number_format(intval(substr($val,0,strlen($val)-2)),).'.'.substr($val,-2);

the first substr will just forget the two last digits and then will be formated with only thousand separator. the second substr just take the two last numbers.

artragis
  • 3,677
  • 1
  • 18
  • 30
1
setlocale(LC_MONETARY, 'en_US');
echo '$' . money_format('%i', $number/100) . "\n";
dave
  • 62,300
  • 5
  • 72
  • 93