How i can convert a number in table to 6-digit decimal?
54 views (last 30 days)
Show older comments
Based on the table above,how to convert numbers in table to 6 digit decimal, thank you for your attention and solution
0 Comments
Accepted Answer
Cameron
on 22 Mar 2023
Do you mean 6 total digits or 6 digits after the decimal? For 6 total digits, you can do this:
T = ([1:10;pi:pi:10*pi])';
MyArray = strings(size(T));
for row = 1:size(T,1)
for col = 1:size(T,2)
MyArray(row,col) = regexprep(sprintf('%#.7g',T(row,col)),'.$','');
end
end
disp(MyArray)
For 6 digits after the decimal, you can do this:
T = ([1:10;pi:pi:10*pi])';
MyArray = strings(size(T));
for row = 1:size(T,1)
for col = 1:size(T,2)
MyArray(row,col) = sprintf('%.6f',T(row,col));
end
end
disp(MyArray)
More Answers (1)
Adam Danz
on 22 Mar 2023
Do you want to round your data to 6 decimal places or do you want to only display 6 decimal places?
Rounding data
There should be a good motivation to round your data since rounding reduces precision.
If the table T only contains numeric values, to round to 6 decimal places,
format long % for demo purposes; use "format default" to revert to default
T = table(randi(9,6,1),rand(6,1),rand(6,1))
T = round(T,6)
If there are non-numeric values, you must index the numeric columns,
T = table(randi(9,6,1),rand(6,1),rand(6,1),["A";"B";"C";"D";"E";"F"])
isnum = varfun(@isnumeric,T,'OutputFormat','uniform');
T(:,isnum) = round(T(:,isnum),6)
Limiting the display
One way to limit the display of all numeric values is to use the DisplayFormatOptions function (R2021a and later) or to set the format(style). However, options are limited to a predefined list of formats and numeric values that have fewer decimal places will not be padded. MATLAB does not show trailing 0s. This willl change the display of all numeric values in the command window.
The only way to show a specific number of decimal places with padded 0s is to convert the numeric values to strings (or characters or categoricals). This makes the numeric values more difficult to work with in MATLAB since they are no longer numbers. The for-loops @Cameron shared in the other answer is one way to achieve this. This method below only acts on columns of numeric data.
T = table(randi(9,6,1),rand(6,1),rand(6,1),["A";"B";"C";"D";"E";"F"])
isnum = varfun(@isnumeric,T,'OutputFormat','uniform');
T = convertvars(T,isnum,'string'); % R2018b or later
T(:,isnum) = arrayfun(@(n) {sprintf('%.6f',n)},T{:,isnum})
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!