Rounding to n significant digits

前端 未结 1 862
挽巷
挽巷 2020-12-04 01:52

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?

相关标签:
1条回答
  • 2020-12-04 02:48

    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
    
    0 讨论(0)
提交回复
热议问题