str2double goes wrong for very large numbers

Hi I am trying to convert large string IDs to numeric but something goes wrong. The original string is converted but not to the correct number.
What is the correct solution and why is this happening?
>> sprintf('%21.0f',(str2double('1032400774240044774')))
ans =
' 1032400774240044800'

 採用された回答

Stephen23
Stephen23 2018 年 6 月 27 日
編集済み: Stephen23 2018 年 6 月 27 日

1 投票

'1032400774240044774' has nineteen digits, which is greater than flintmax: there is no way that this value can be represented using a double and maintain precision down to the ones. This is simply impossible using standard floating point numbers:
If you want to get the full precision then you will need to store it as an integer type, e.g. by converting to uint64 using sscanf:
>> n = sscanf('1032400774240044774','%lu')
n =
1032400774240044774
>> sprintf('%u',n)
ans =
1032400774240044774
Note that you cannot use %f for the sprint format because then it will be internally converted to floating point.
Integer types also have a maximum limit:
>> intmax('uint64')
ans =
18446744073709551615
If you want to store larger numbers than that, then you could use the symbolic toolbox, or store them as strings, or use one of the large integer classes available on FEX, e.g.:

1 件のコメント

Alex B
Alex B 2018 年 6 月 27 日
編集済み: Alex B 2018 年 6 月 27 日
Hi Stephen,
Thank you for the quick response, much appreciated!
Best, Alex

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeData Type Conversion についてさらに検索

質問済み:

2018 年 6 月 27 日

編集済み:

2018 年 6 月 27 日

Community Treasure Hunt

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

Start Hunting!

Translated by