#### Archived

This topic is now archived and is closed to further replies.

# Easier way for rounding several values?

## 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?

##### 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

##### 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

##### Share on other sites
Agreed Ken,

That's a lot easier to understand and maintain.

Jeff

##### 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]
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]