How I can modify the decimal numbers in a table's column?

I have a table with different values like: 0.5, -0.300, -99, 5, 0, and so on. I want to use the output of this table in a hydrological model so I need to have all values in 1 decimal (even integer values, like 5).
Here is an example:
-5.40000000000000
-2.20000000000000
-3.40000000000000
5
4
-99
0
Are what I have, But I need something like this:
-5.4
-2.2
-3.4
5.0
4.0
-99.0
0.0
I tried something like format long, format long g, and format bank, but they weren't helpful. So if anyone knows the solution I would be grateful if tells me.
Best regards

 Respuesta aceptada

a = randn(5,1)
a = 5×1
0.1370 -0.9759 -1.3119 2.0201 1.3604
str = sprintf('%.1f\n', a)
str =
'0.1 -1.0 -1.3 2.0 1.4 '

6 comentarios

it creates string not answering the question I think...
Gabor
Gabor el 23 de Oct. de 2023
This is NOT an ANSWER to the QUESTION!
Gabor
Gabor el 23 de Oct. de 2023
This is the answer:
Table.Column=round(Table.Column,1);
Gabor
Gabor el 8 de Nov. de 2023
Editada: Gabor el 8 de Nov. de 2023
actually if you do: Table.Column=round(Table.Column,1); its not working..... not sure why this simple task wont work!!!
Actually the only way worked for me unfortunately:
Table.Colum = num2str(Table.Colum, '%.2f');
Not an ideal solution because it becomes a string, but when you open the table you will see the numbers in strings how it should look.
format long g
Column = randn(5,1)
Column = 5×1
-0.474707105013206 1.4443908607698 1.76341706465071 -1.3245954736747 -0.388849281393544
Table = table(Column)
Table = 5×1 table
Column __________________ -0.474707105013206 1.4443908607698 1.76341706465071 -1.3245954736747 -0.388849281393544
Table.Column=round(Table.Column,1)
Table = 5×1 table
Column ______ -0.5 1.4 1.8 -1.3 -0.4
format short
Table
Table = 5×1 table
Column ______ -0.5 1.4 1.8 -1.3 -0.4
Looks to me as if it is working?
for exactly 2 decimal places, if you are using uitable() then set the uitable ColumnFormat property to 'bank'
Note that "bank" format rounds numbers. If you happened to be doing financial work then in some cases, floor is prefered to rounding; in such a situation you should use the somewhat-new round TieBreaker option.

Iniciar sesión para comentar.

Más respuestas (1)

You want to display the numbers as shown or modify them? In case you want to modify them, you can use
number = -99.32345; % the number you want to modify
num_str = num2str(number); % convert it to string
[idx,~]=regexp(num_str,'[.]'); % search for decimal point
num_str(idx+2:end) = []; % delete everything from idx+2 till end
number = str2num(num_str) % convert result back to number
You can use this in a loop to modify all of your values.

Categorías

Productos

Versión

R2020a

Etiquetas

Preguntada:

BN
el 5 de Ag. de 2021

Comentada:

el 8 de Nov. de 2023

Community Treasure Hunt

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

Start Hunting!

Translated by