Convert decimal number to vector

▼魔方 西西 提交于 2019-12-02 12:21:11
Andrew Janke

What input source are you getting those numbers from? And are all those digits significant? Your example numbers are already beyond the relative precision of the double numeric type. The eps function will tell you how much roundoff you're getting.

>> sprintf('%.20f', 12345.6788993442355456789)
ans =
12345.67889934423500000000
>> eps(12345.6788993442355456789)
ans =
    1.818989403545857e-012
>> sprintf('%.20f', 23432.23432345678911111111111100998)
ans =
23432.23432345678900000000
>> eps(23432.23432345678911111111111100998)
ans =
    3.637978807091713e-012

When you type a number in to Matlab source code, it's treated as a literal of type double. So many of those digits are lost as soon as you enter them. See this question for more discussion: In MATLAB, are variables REALLY double-precision by default?.

If you really want to preserve all those digits, you need to avoid storing them in doubles in the first place. Start off with the full number in a string, and then parse it.

function out = parseLongDecimal(str)
ixDot = find(str == '.');
if isempty(ixDot)
    out.whole = arrayfun(@str2double, str);
    out.fraction = [];
else
    out.whole = arrayfun(@str2double, str(1:ixDot-1));
    out.fraction = arrayfun(@str2double, str(ixDot+1:end));
end

That will preserve all the digits.

>> xAsStr = '23432.23432345678911111111111100998';  % as a string literal, not numeric
>> parseLongDecimal(xAsStr)
ans = 
       whole: [2 3 4 3 2]
    fraction: [2 3 4 3 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 1 1 0 0 9 9 8]

Depending on your use case, you could also just throw it in a Java BigDecimal object and work with it there.

>> jx = java.math.BigDecimal(xAsStr)
jx =
23432.23432345678911111111111100998

Also using num2str, you can do:

sol=arrayfun(@str2num,(sprintf('%f',23432.23432)),'UniformOutput',0)
horzcat(sol{:})

ans =

     2     3     4     3     2     2     3     4     3

Do you want to keep the information about where is the comma?

Not familiar with Matlab syntax but if you

  • convert the number to a string
  • loop through each character and add the digit to the vector if the character is not the decimal point

that would work. There are probably more efficient ways to do this.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!