Converting string to a double
8 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hello everyone.
i'm programming a software that gets different values from a txt file, and plotting a graph based on these values.
In order to create the graph I had to convert the strings in the txt file to a double, but the str2double function rounds the values so the graph isn't accurate.
for example, the string to convert is: 1.7356922617E-3, and the doublue value after applying the method is 1.73569E-3.
is there any method that convert without rounding?
thank you.
1 comentario
Stephen23
el 24 de Mzo. de 2021
Editada: Stephen23
el 24 de Mzo. de 2021
" but the str2double function rounds the values so the graph isn't accurate."
I very much doubt that str2double "rounds the values", what is much more likely is that you are confusing how numeric data are displayed with how numeric data are stored, which are two completely different things.
You can easily change how the data are displayed:
format short
str = '1.7356922617E-3';
val = str2double(str)
format long
val
So str2double has not "rounded" the value at all, all of the digits are converted and stored as expected.
Respuestas (1)
Fangjun Jiang
el 24 de Mzo. de 2021
Are you sure?
>> format long
>> a=str2double('1.7356922617E-3')
a =
0.001735692261700
7 comentarios
Walter Roberson
el 24 de Mzo. de 2021
c=str2double('10.12345678901234567890')
fprintf('%.999g\n', c)
This has apparently remembered 16 total digits correctly, 10.12345678901234. Is that really the case?
fprintf('%.999g\n', 10.12345678901234567890) %do we get the same?
fprintf('%.999g\n', 10.123456789012340)
fprintf('%.999g\n', 10.123456789012344)
fprintf('%.999g\n', 10.123456789012345)
fprintf('%.999g\n', 10.123456789012346)
fprintf('%.999g\n', 10.123456789012350)
fprintf('%.999g\n', 10.12345678901234567890*(1-eps))
fprintf('%.999g\n', 10.12345678901234567890*(1+eps))
So after 10.12345678901234 it is taking into account that what follows is something on the high side of 5x in order to decide whether to round down to 10.123456789012344 or up to 10.123456789012346
Fangjun Jiang
el 24 de Mzo. de 2021
good points. Now I understand better. It certainly can read in more than 15 digits after decimal point.
>> p1=sprintf('%40.30f',pi)
p1 =
' 3.141592653589793115997963468544'
>> d=str2double(p1)
d =
3.141592653589793
>> p2=sprintf('%40.30f',d)
p2 =
' 3.141592653589793115997963468544'
Ver también
Categorías
Más información sobre Data Type Conversion en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!