Precision in writetable()

89 ビュー (過去 30 日間)
madhan ravi
madhan ravi 2020 年 10 月 26 日
コメント済み: dpb 2025 年 4 月 16 日
Is there a way to use writetable() to export using only 2 decimals? To be able to directly export it to an excel file.

採用された回答

dpb
dpb 2020 年 10 月 26 日
Sadly, no. A OutputFormat formatting string or NumericPrecision option is not available.
I presume since a table can contain any data type including cells too many possibilities are opened up that TMW hasn't wanted to venture down that road.
Does seem like worthy of some design consideration for the normal cases, though, granted...
For text files, the numeric format is long g.
  7 件のコメント
Tao Wang
Tao Wang 2022 年 3 月 10 日
For me , Willingo's answer is still not working.
I tried and it did show numbers with 2 decimals in commond . but if I writetable() to excel, the numbers format is still long.
Also , I tried num2str first ,
num2str(1.345,'%.2')
and u will not only get the data with 2 decimals ,but also a green flag on the top left of the box.
dpb
dpb 2022 年 3 月 10 日
Because having rounded the numbers, they still are doubles and will have machine-precision rounding that Excel will try to preserve.
All you can do is format them inside Excel; same way as MATLAB, Excel keeps everything as a double internally; it only changes how they're displayed.
The second route writes the numeric value as text in the cell which is the source of the warning highlight.
There are several user-contributed utilities to allow one to set Excel table properties on the FEX. I believe it was @Image Analyst who wrote and posted a pretty nice starter set of Excel_utils that you may search for here on Answers -- I recall making a couple extensions and adding/posting another feature or two. That's been with the year...just at the moment I've got things in a state it isn't convenient to try to go find, but will try to get back...

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

その他の回答 (2 件)

Johannes Kalliauer
Johannes Kalliauer 2022 年 7 月 20 日
編集済み: Johannes Kalliauer 2022 年 7 月 20 日
dlmwrite('yourfile.txt',t{:,:},'\t','precision','%10.2f')
  1 件のコメント
dpb
dpb 2022 年 7 月 20 日
Doesn't get OP directly to Excel as per request, though...but correct that it does allow the formatting string.

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


Christine
Christine 2025 年 2 月 12 日
Another workaround might be executing this line for the variables inside the table.
variable = round(variable*100)/100;
  2 件のコメント
Adam Danz
Adam Danz 2025 年 4 月 16 日
Use Y = round(X,N) to specify the number of decimal places.
Instead of
round(pi*100)/100
ans = 3.1400
use
round(pi,2)
ans = 3.1400
dpb
dpb 2025 年 4 月 16 日
Another I've seen has been
str2double(sprintf('%.2f',pi))
ans = 3.1400

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

カテゴリ

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

タグ

製品


リリース

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by