4.25

4.2 | 4 ratings Rate this file 16 Downloads (last 30 days) File Size: 2.74 KB File ID: #10669

Significant Figures

by Teck Por Lim

 

07 Apr 2006 (Updated 09 Mar 2009)

Workaround for fprintf/sprintf to produce correct output for signficant figures, as fprintf/sprintf

| Watch this File

File Information
Description

[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"

MATLAB release MATLAB 7 (R14)
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Comments and Ratings (4)
26 May 2006 your friend  
30 Apr 2007 Johan Lans

Simple script that does an excellent job. Works fine with sprintf().

19 Feb 2008 Who Doc  
18 Aug 2008 Bug Report

Perhaps this is a Matlab R2008b quirk...but when I enter "sigfig(0.999,2)" I get "0.100" - off by an order of magnitude.

Please login to add a comment or rating.
Updates
10 Apr 2006

Update help

23 May 2006

1 bug fixed.
Changes to code.
Can accept matrices now.
Example file provided.

27 Apr 2007

More satisfactory behaviour for end of line behaviour, and small changes.

22 Feb 2008

Changes in code and example

03 Mar 2008

To enable sigfig(nan)

19 Nov 2008

Bug fixed.

23 Nov 2008

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

24 Nov 2008

Updated description.

15 Jan 2009

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

09 Mar 2009

Support for Inf and -Inf

Tag Activity for this File
Tag Applied By Date/Time
strings Teck Por Lim 22 Oct 2008 08:21:41
significant figures Teck Por Lim 22 Oct 2008 08:21:41
workaround Teck Por Lim 22 Oct 2008 08:21:42
round Teck Por Lim 05 Dec 2008 12:26:17

Contact us at files@mathworks.com