Created
April 4, 2018 12:58
-
-
Save bencholmes/180b9c8477e316fa757a9b7e3e05d9a0 to your computer and use it in GitHub Desktop.
A MATLAB function to convert from component value to formatted string with engineering suffix.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function string = engFormat(value, type) | |
%ENGFORMAT a function to take a passive electronic component value and | |
% return a string with the properly formatted suffix. | |
aVal = abs(value); | |
nn = 0; | |
if strcmp(type,'R') | |
type = char(937); | |
end | |
if strcmp(type,'C') | |
type = 'F'; | |
end | |
if strcmp(type,'L') | |
type = 'H'; | |
end | |
if aVal>=1 | |
while aVal*10^(-nn) > 10 | |
nn = nn+1; | |
end | |
positive = {' ', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'}; | |
ind = min(floor(nn/3), length(positive)-1); | |
nDigits = nn - 3*floor(nn/3) + 1; | |
string = sprintf('%s%.4f %s%s',repmat(' ',1,3-nDigits), value*10^(-3*ind), positive{ind+1}, type); | |
else | |
while aVal*10^(-nn) < 1 | |
nn = nn - 1; | |
end | |
negative = {' ', 'm', char(956), 'n', 'p', 'f', 'a', 'z', 'y'}; | |
ind = min(ceil(-nn/3), length(negative)-1); | |
nDigits = 3*ceil(-nn/3) + nn + 1; | |
string = sprintf('%s%.4f %s%s', repmat(' ',1,3-nDigits), value*10^(3*ind), negative{ind+1}, type); | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment