Rounding to n significant digits

13,116

To round to d significant digits:

>> d = 3; %// number of digits
>> x = 5.237234; %// example number

>> D = 10^(d-ceil(log10(x)));
>> y = round(x*D)/D
y =
    5.2400

To round to d decimal digits:

>> d = 3; %// number of digits
>> x = 5.237234; %// example number

>> D = 10^d;
>> y = round(x*D)/D
y =
    5.2370

EDIT

Actually it's easier: the round function supports these options:

>> d = 3;
>> x = 5.237234;
>> y = round(x, d, 'significant')
y =
    5.2400

>> d = 3;
>> x = 5.237234;
>> y = round(x, d) %// or y = round(x, d, 'decimals')
y =
    5.2370
Share:
13,116
saharz
Author by

saharz

Updated on August 17, 2022

Comments

  • saharz
    saharz over 1 year

    I'm trying to write code in MATLAB that will round number to certain (as I ask) significant digits.

    I'm not sure how to do it. Any suggestions?

  • saharz
    saharz over 9 years
    why b(2)=b(3) b=[sdround(pi/4,3),sdround(pi/4,4),sdround(pi/4,9)] b = 0.7850 0.7854 0.7854
  • Luis Mendo
    Luis Mendo over 9 years
    @saharz That's just a displaying issue. Try format long
  • dmckee --- ex-moderator kitten
    dmckee --- ex-moderator kitten over 6 years
    Note that octave doesn't have the upgraded round function, so the earlier part of this answer is still useful for open source users.