Is there a way to retain the precision of the zero?

11 次查看(过去 30 天)
I have a large string array with 0.000000, but when I convert it to a matrix through 'num2str' it is converted into 0. I have tried format long, etc. but it only affects the numbers other than zero.
  1 个评论
Stephen23
Stephen23 2017-2-26
编辑:Stephen23 2017-2-26
"I have tried format long, etc. but it only affects the numbers other than zero"
Changing the format makes absolutely no difference to the precision of the variable stored in memory, only to how they are displayed. Here is an example:
>> X = 2.009
X =
2.009
>> format bank
>> X
X =
2.01
>> X*100
ans =
200.90
The last step above shows that format bank does not change the precision of the stored variable whatsoever: it still retains all digits of precision that it had when it was defined.
Zero is stored with exactly the same precision as any other values of the same class. You cannot change its stored precision for one class, only its displayed precision.

请先登录,再进行评论。

回答(2 个)

Star Strider
Star Strider 2017-2-26
If the string representation is just '0.000000', the str2num result double(0) is nnumerically as precise as it’s going to get! It has the full precision internally.

Walter Roberson
Walter Roberson 2017-2-26
Assuming that numbers are not in scientific format,
num_decimals = cellfun(@length, regexprep(YourCell, '^\d*\.', ''));
as_num = str2double(YourCell);
Now, as_num is the numeric value of YourCell, and num_decimals is the number of digits after the decimal point associated with each entry.
If at some point you need to print them back out with the original number of decimal places, then
delimiter = ' ';
fmt = [repmat( ['%.*f', delimiter], 1, size(as_num,2)-1), '%.*f\n'];
temp = [ num2cell(num_decimals(:)) .'; num2cell(as_num(:)) .'];
fprintf( fmt, temp{:} )
Remember, the number of 0's printed out is a matter of display, not of what is actually stored. What is actually stored is binary rather than decimal.

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by