Forum Moderators: coopster

Message Too Old, No Replies

CSV decimal format

fgetcsv format decimal field

         

jspeed

6:42 pm on Aug 19, 2011 (gmt 0)

10+ Year Member



Hello, i'm reading a CSV file in PHP. Everything works correctly, I am trying to figure out how to format a "cell" out of the CSV that displays multiple decimals. I would like it to only display 2 decimals, so to the hundredths place. (e.g. $4.562 to $4.52) and likewise round up if needed.

$file = fopen ("contents.csv","r");
$info = fgetcsv ($file, 1000, ",");
echo $info[4];

I've tried a couple examples posted in the php manual, but have not had success. Could someone help me connect the dots please? The code below works well, but I don't know how to integrate $info[4] as the variable to round.

function round_up ( $value, $precision ) {

$pow = pow ( 10, $precision );

return ( ceil ( $pow * $value ) + ceil ( $pow * $value - ceil ( $pow * $value ) ) ) / $pow;

}

var_dump ( round_up ( 499.9440000046, 2 ) ); // float(499.95)

Thanks for any help

lostdreamer

9:33 pm on Aug 21, 2011 (gmt 0)

10+ Year Member




$file = fopen ("contents.csv","r");
$info = fgetcsv ($file, 1000, ",");
echo round($info[4], 2);


Should do it

and drop the round_up function, you dont need to rewrite internal functions ;)

jspeed

3:20 pm on Aug 23, 2011 (gmt 0)

10+ Year Member



Friend, thank you!