How to set a specified number of digits when exporting to excel?

47 views (last 30 days)
Hi,
I have an array
a=[101.13123124,99.329040,201.329524,2094.302785];
Could someone tell me how to write the array to excel with 4 digits as I set format short in the command window?
As
a=[101.1312,99.3290,201.3295,2094.3027];
How about other number of digits such as 3 digits.
My code:
clc
clear all
format short
filename=input('Name file output: ','s');
fileadd=strcat('c:\',filename,'.xlsx');
a=[101.13123124,99.329040,201.329524,2094.302785];
xlswrite(fileadd,a,1,'A6');
Thanks

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 4 Oct 2014
Edited: Azzi Abdelmalek on 4 Oct 2014
a=[101.13123124,99.329040,201.329524,2094.302785]
b=arrayfun(@(x) sprintf('%10.4f',x),a,'un',0)
xlswrite('file.xlsx',b)

More Answers (1)

Image Analyst
Image Analyst on 4 Oct 2014
Rather than throwing away precision, I'd recommend using either ActiveX, where you can tell Excel to set the number of decimal places to whatever you want, or just have a template with that precision set up in advance. If you want to learn ActiveX, I've attached a demo, though this is a simple demo so I don't have code in there to set the number of decimal points (available upon request).. If you think it's too advanced for you, then use Azzi's method which does exactly what you asked for.
  3 Comments
karthik tharanisingh
karthik tharanisingh on 12 Nov 2021
Hello @Image Analyst. I just happened to fall onto this thread and I am looking for a way to round the values in Excel though ActXserver. I went through your code and generally gave me a great insight into how to use ActXserver. I would be interested in knowing about the rounding as well.
Image Analyst
Image Analyst on 12 Nov 2021
You can round the displayed values by setting the number of decimal points. I have a function for that in my attached class.
Otherwise you can use the MATLAB round() function to round them before sending to Excel.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!