Rounding values to a defined number of significant digits

This function uses the built-in 'round' function and exploits text search to temporary shift the decimal place. Just another example of more elaborate rounding. The output is the rounded value of the input, e.g. rounding 0.003474 to two digits yields 0.0035. Does currently not work correctly with negative inputs. But this would be easily implemented by separating out the sign.
Function SuperRound(number,digits)                   // round values to selectable number of digits
    Variable number, digits
    String StrNumber
    Variable Multiplier, i                           // multiplier decides how much the decimal spot is "shifted" for rounding
    if (number < 1)                              // separate numbers whether they are < or > 1
        sprintf StrNumber, "%.10f", number           // express the number as text to work with it
        for (i = 2; i < Strlen(StrNumber); i += 1)
            if(StringMatch(StrNumber[i],"0") == 0)       // find the first non-zero number
                Multiplier = 10^(2 - i - digits)
        sprintf StrNumber, "%d", number              // express the number as text to count the digits
        Multiplier = 10^(strlen(StrNumber) - digits)
    if (Multiplier < 1)                          // countermeasure for rounding errors when dividing by small numbers
        Multiplier = 1/Multiplier
        number = round(number*Multiplier)/Multiplier   
        number = round(number/Multiplier)*Multiplier
    return number
Why not just let sprintf do the heavy lifting?

Function DoStuff(value, numSigDigits)
    variable value, numSigDigits

    string str

    sprintf str, "%.*g\r", numSigDigits, value

    return str2num(str)

print DoStuff(0.003474, 2) 0.0035
I was somehow under the impression that str2num() is limited and wanted to avoid that function. But looking again only num2str() has limitations it seems. Of course there are elegant ways to round. My initial starting point was to exploit the round() function. One can see it as an example in number handling then.




Igor Pro 9

Learn More

Igor XOP Toolkit

Learn More

Igor NIDAQ Tools MX

Learn More