Jump to content

Easier way for rounding several values?


EngineeringGuy

Recommended Posts

I am sure there is an easier way to do this but I don't yet know how to do it.  Is there a way I can perform the round function to the following:

[code]//First we round the values to get sig figs. We don't round the first value since its the NPS
$sigfig="2"; /number of decimal values
$col2=round($col2,$sigfig);
$col3=round($col3,$sigfig);
$col4=round($col4,$sigfig);
$col5=round($col5,$sigfig);
$col6=round($col6,$sigfig);
$col7=round($col7,$sigfig);
$col8=round($col8,$sigfig);
$col9=round($col9,$sigfig);
$col10=round($col10,$sigfig);
$col11=round($col11,$sigfig);
$col12=round($col12,$sigfig);
$col13=round($col13,$sigfig);
$col14=round($col14,$sigfig);
$col15=round($col15,$sigfig);[/code]

This gets tedious to write over and over. . . maybe I could use a For function?
Link to comment
Share on other sites

[code]
$sigfig = 2;

for ($i = 2; $i < 15; $i ++) //  use a bigger number if 15 is too small
{
    $var  = "col$i";                        // store the working var name col2, col3, etc...
    $$var = round($$var, $sigfig); // set and round the variable named 'col2', 'col3', etc...
}
[/code]

Jeff
Link to comment
Share on other sites

You also may want to change your code to use an array instead of many variables:
[code]<?php
//First we round the values to get sig figs. We don't round the first value since its the NPS
$sigfig=2; //number of decimal values 
for($i=2;$i<count($col);$i++)
    $col[$i] = round($col[$i],$sigfig);
?>[/code]

Ken
Link to comment
Share on other sites

[quote author=kenrbnsn link=topic=107589.msg431903#msg431903 date=1157949420]
You also may want to change your code to use an array instead of many variables:
[code]<?php
//First we round the values to get sig figs. We don't round the first value since its the NPS
$sigfig=2; //number of decimal values 
for($i=2;$i<count($col);$i++)
    $col[$i] = round($col[$i],$sigfig);
?>[/code]
Unecessary with the use of array_walk():

[code]<?php

$array = array(1.111,2.222,3.333);

array_walk($array, create_function('&$a,$b,$c', '$a = round($a, $c);'), 2);

var_dump($array);

?>[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.