フィルターのクリア

json char with too many decimals, need removal

3 ビュー (過去 30 日間)
Martin
Martin 2021 年 5 月 29 日
コメント済み: Rik 2021 年 5 月 31 日
I got some json str = '{"hund": 0.3253533250000000000000000000000000, "kat": "dfsdfs", "baenkebider": 0.002021203321320000000000000000000000}';
In reality its a longer string with even more figures. I need to remove all those long decimals. 7-8 decimals is enough, so I end up with something like:
str = '{"hund": 0.3253533, "kat": "dfsdfs", "baenkebider": 0.0020212}';
If someone can help with an elegant solution I will appreciate it a lot!
Thanks in advance,
-best
mergh
  3 件のコメント
Martin
Martin 2021 年 5 月 30 日
Thanks for answering. join() and isfinite() is however a bit messy with regards to the cell piece.
dpb
dpb 2021 年 5 月 30 日
I knew Stephen or similar would be along...
You'll note I specifically did NOT say it was elegant... :)

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

採用された回答

Stephen23
Stephen23 2021 年 5 月 30 日
編集済み: Stephen23 2021 年 5 月 31 日
str = '{"hund": 0.3253533250000000000000000000000000, "kat": "dfsdfs", "baenkebider": 0.002021203321320000000000000000000000}';
Method one (truncate to 9 characters):
out = regexprep(str,'\d+\.\d+','${$&(1:9)}')
out = '{"hund": 0.3253533, "kat": "dfsdfs", "baenkebider": 0.0020212}'
Method two (seven fractional digits):
fun = @(s)sprintf('%.7f',sscanf(s,'%f'));
out = regexprep(str,'\d+\.\d+','${fun($&)}')
out = '{"hund": 0.3253533, "kat": "dfsdfs", "baenkebider": 0.0020212}'
  2 件のコメント
Martin
Martin 2021 年 5 月 30 日
wow, thanks!
Rik
Rik 2021 年 5 月 31 日
This will of course not work on an arbitrary JSON string, so you need to be careful if you want to do so. You could consider using a custom JSON encoder that allows you to trim trailing 0 in decimal notation.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeJSON Format についてさらに検索

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by