Convert decimal number to vector

2019-03-05 07:28发布

问题:

In matlab I want to convert this:

12345.6788993442355456789

into a vector

[1 2 3 4 5 6 7 8 8 9 9 3 4 4 2 3 5 5 4 5 6 7 8 9]

I have found several solutions to convert a integer into a vector using commands like scanf, num2str,... but those don't fit with non-integers, and some solutions have problems with numbers with a large number of decimal places...

That kind of conversion is needed because I want to see and use all of the digits of the number.

回答1:

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


回答2:

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?



回答3:

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.