Converting string to a double
조회 수: 20 (최근 30일)
이전 댓글 표시
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
Stephen23
2021년 3월 24일
편집: Stephen23
2021년 3월 24일
" 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.
답변 (1개)
Fangjun Jiang
2021년 3월 24일
Are you sure?
>> format long
>> a=str2double('1.7356922617E-3')
a =
0.001735692261700
댓글 수: 7
Walter Roberson
2021년 3월 24일
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
2021년 3월 24일
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'
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!