File Exchange

image thumbnail

Round values after the decimal point

version 1.3.0.0 (1.6 KB) by Tobias Otto
Rounding values at a defined place after the decimal point.

1 Download

Updated 28 Apr 2011

View Version History

View License

Useful helper function that rounds scalars, vectors or matrices smaller/bigger than zero at a defined place after the decimal point.
Needs two input arguments to work properly: out = sRound(val, precision)

Usage: out = sRound(val, prec)

Example1: a = sRound(0.46,1);
a = 0.5000

Example2: b = sRound(-5.478,2);
b = -5.4800

Example3: c = sRound([0.8236 2.6958 3.3171 0.9502 0.0364], 3);
c = 0.8240 2.6960 3.3170 0.9500 0.0360 0.34330

Example4: d = sRound([-0.1694 -1.4351 0.3925; -0.0522 -2.6 1.3433], 3);
d = -0.1690 -1.4350 0.3930
-0.0520 -2.6000 1.3430
Example5: e = sRound(3.5);
e = 4

This code should run with every MATLAB version.

Cite As

Tobias Otto (2021). Round values after the decimal point (https://www.mathworks.com/matlabcentral/fileexchange/31209-round-values-after-the-decimal-point), MATLAB Central File Exchange. Retrieved .

Comments and Ratings (3)

Jan

* The expanded user info is helpful.
* You are right: NARGIN > 2 is caught by Matlab already.
* While "prec=10^prec" is indeed necessary, "res=val - floor(val)" and adding the fractional and integer part afterwards again is not. I get the same result by: "prec = 10^prec; out = round(val * prec) / prec;".

Tobias Otto

Hi Jan, thank you for your Comments and suggestions.
* I've added more user info and examples

* Error handling for nargin>2 is done by MATLAB. Please check:sRound(3.21,2,2)
??? Error using ==> sRound
Too many input arguments.
Everything else is handled in sRound.

* prec = 10^prec; is necessary for my function to work. Please double check my code or simply comment out the line and check yourself.

Jan

See also: http://www.mathworks.com/matlabcentral/fileexchange/6077-round2 and http://www.mathworks.com/matlabcentral/fileexchange/6076-fix2.
The checks for the number of inputs does not catch more than 2 inputs. "if nargin==1, prec=0; elseif nargin ~= 2, error(), end" would be exhaustive.
Splitting the input into integer and fractional part is not needed. "prec = 10^prec;
out = round(val*prec)/prec;" would be sufficient.
It would be helpful, if you explain the type and dimensions of the accepted input (DOUBLE and SINGLE? Arrays or just scalar?).

MATLAB Release Compatibility
Created with R2011a
Compatible with any release
Platform Compatibility
Windows macOS Linux
Acknowledgements

Inspired: Average_precision(Outputs,test_target)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!