Significant Figures

Workaround for fprintf/sprintf to produce correct output for signficant figures, as fprintf/sprintf
1.8K Downloads
Updated 9 Mar 2009

View License

[strOut] = sigfig(num, nSigFig, dummy)
Rounds number to nSigFig number of significant figures and outputs a string Dummy in 3rd argument to have padded zeros
Lim Teck Por, 2006, 2008,2009

Apropos: mat2str, num2str, sprintf
This code serves as a workaround to rounding problems probably caused by converting from base 10 to base 2 prematurely (Note that this problem can also be found in C and python) and print zero padding:

num2str(3.15, 2)
mat2str(3.15, 2)
fprintf('%1.2g\n', 3.15)
sprintf('%1.2g\n', 3.15)
give 3.1 instead of 3.2 whereas an input of 3.75 gives 3.8.

sigfig(3.15, 2) gives "3.2"
sigfig(3.75, 2, []) gives "3.8e+0"

Cite As

Teck Por Lim (2024). Significant Figures (https://www.mathworks.com/matlabcentral/fileexchange/10669-significant-figures), MATLAB Central File Exchange. Retrieved .

MATLAB Release Compatibility
Created with R14
Compatible with any release
Platform Compatibility
Windows macOS Linux
Categories
Find more on ROS Log Files and Transformations in Help Center and MATLAB Answers

Community Treasure Hunt

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

Start Hunting!
Version Published Release Notes
1.8.0.0

Support for Inf and -Inf

1.6.0.0

Allowed default nargin < 2 to mean number of significant figures = 3
Updated example.m

1.5.0.0

Updated description.

1.4.0.0

Fixed bug with sigfig(99.9999,2).
Removed leading zeros from exponent.

1.3.0.0

Bug fixed.

1.0.0.0

To enable sigfig(nan)