Can I specify the numeric precision for each column when exporting the table data using writetable?

I would like to specify the numeric precision for each column when exporting the table data using writetable function.
For example, in the following dataset, I would like to set A column to the last one digit and B column to the last three digits.
>> data = [(1:3)', rand(3,1)];
>> T = array2table(data,'VariableName',{'A','B'})
T =
A B
_ _______
1 0.81472
2 0.90579
3 0.12699
>> writetable(T,'mydata.csv','WriteRowNames',true)

 Accepted Answer

There is no ability to specify the numeric precision for writetable. "writetable" outputs numeric variables using long g format.
To workaround, you can use num2str function to convert a numeric value to a character string.
>> T.A = num2str(T.A,'%1.1f\n');
>> T.B = num2str(T.B,'%1.3f\n');
>> T
T =
A B
___ _____
1.0 0.815
2.0 0.906
3.0 0.127
>> writetable(T,'mydata.csv','WriteRowNames',true)
>> type mydata.csv
A,B
1.0,0.815
2.0,0.906
3.0,0.127

2 Comments

The above has a disadvantage in that it changes the actual table data itself which may be undesireable and requires modifying each column independently.
Beginning with R2017a, one could create the rounded text on the fly as a temporary using the vectorized compose function to format and writecell beginning with R2019a to output the file.
AB=[1 0.81472
2 0.90579
3 0.12699];
T=array2table(AB,'VariableNames',{'A','B'});
writecell(compose('%0.1f,%0.3f',T.A,T.B),'AB.csv','QuoteStrings',0)
type AB.csv
1.0,0.815 2.0,0.906 3.0,0.127
Just a little more modern syntax, maybe, as another route to consider...but certainly the ability to specify a display/output format for table variables would be a most welcome enhancement....as another use case/justification, I've been dealing with a lot of financial data for local community college foundation last several years and while format bank, format compact is helpful for the financial columns, it is painful that 8-digit integer IDs then are also forced to have ".00" appended to them.
To play fair, using writetable does get the variable names to come along for the ride if needed/wanted while it takes a little more effort to do them this way to format them and add to the cell array before writing it out.
ADDENDUM
Adding the variable names and also referring to the whole table as an array -- since the variable names are returned as a cellstr array, simply JOINing them with the delimiter suffices.
writecell([join(T.Properties.VariableNames,',');compose('%0.1f,%0.3f',T{:,:})],'AB.csv','QuoteStrings',0)
type AB.csv
A,B 1.0,0.815 2.0,0.906 3.0,0.127
varfun can come in handy for converting all numeric variables in a table to desired format(s).

Sign in to comment.

More Answers (0)

Categories

Products

Release

R2015b

Asked:

on 24 Sep 2026 at 0:00

Edited:

dpb
on 26 Sep 2026 at 13:14

Community Treasure Hunt

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

Start Hunting!