# Easier way for rounding several values?

5 replies to this topic

### #1 EngineeringGuy

EngineeringGuy
• Members
• Member
• 12 posts
• LocationBakersfield, CA - 6 feet from Hell

Posted 11 September 2006 - 02:13 AM

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:

```//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);```

This gets tedious to write over and over. . . maybe I could use a For function?

### #2 jefkin

jefkin
• Members
• 55 posts

Posted 11 September 2006 - 03:54 AM

```\$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...
}
```

Jeff

### #3 kenrbnsn

kenrbnsn
• Staff Alumni
• 8,235 posts
• LocationHillsborough, NJ, USA

Posted 11 September 2006 - 04:37 AM

You also may want to change your code to use an array instead of many variables:
```<?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);
?>```

Ken

### #4 jefkin

jefkin
• Members
• 55 posts

Posted 11 September 2006 - 04:40 AM

Agreed Ken,

That's a lot easier to understand and maintain.

Jeff

### #5 Jenk

Jenk
• Members
• 778 posts

Posted 11 September 2006 - 08:28 AM

You also may want to change your code to use an array instead of many variables:
```<?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);
?>```
Unecessary with the use of array_walk():

```<?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);

?>```

### #6 EngineeringGuy

EngineeringGuy
• Members
• Member
• 12 posts
• LocationBakersfield, CA - 6 feet from Hell

Posted 11 September 2006 - 12:01 PM