Precision lost when change numbers to string
28 views (last 30 days)
Hi I am trying to use the following to generate a string. A is is 1D array containing 4 real numbers that have large decimal precisions
A=[0.000002101, 0.000000225567 ,1.20004136789, 66.000052353]
ST=strjoin( string('Hi ') + A.', newline )
However string 'ST' trims or rounds off my numbers. How can I create the string ST with exact numbers in A?
fid = fopen('ny.txt','wt');
fprintf(fid, '%s', ST);
Philip Borghesani on 14 Dec 2017
Similar to how you were doing it:
ST=join("Hi " + num2str(A',"%1.12e"), newline )
Or using sprintf like Walter suggested:
>> sprintf('Hi %1.12e\n',A)
Note that the first method returns a string without a trailing newline and sprintf returns a character vector with one.
More Answers (1)
Walter Roberson on 14 Dec 2017
I am not able to find any documentation establishing that using + between string and number is intended to work at all -- though I know that it is intended to work.
You will need to use sprintf() to do fine-grained formatting of numbers into strings.