Print Friendly and PDF

Round to a Specified Number of Places

Jason -

In GoldSim, the round() function rounds the value a real number X to the nearest integer. Positive values, X, round up to the nearest positive integer when the fractional part of X is greater than or equal to 0.5. Negative values, Y, round down to the nearest negative integer when the absolute value of the fractional part of Y is greater than or equal to 0.5.

But what if you want to specify the number of decimal places to round to? This is fairly easy to implement in an Expression element. The number to be rounded needs to be multiplied by 10 to the power of the number of places, then rounded, then divided by 10 to the power of the number of places. Specifically, assume the number to be rounded is contained in a Data element “X” and the number of digits to the right of the decimal place to round to is contained in a Data element “N” then the equation in the Expression element would be:

round( ( X * 10^N ) ) / 10^N

Note that this expression will also work for rounding to digits to the left of the decimal place if “N” is specified as a negative integer.

Have more questions? Submit a request

Comments