# Transform double to char with one or two decimal places

2 visualizaciones (últimos 30 días)
Alberto Acri el 11 de Sept. de 2023
Comentada: Walter Roberson el 11 de Sept. de 2023
I have a series of numbers:
n_A = 3.15;
n_B = 3.7;
I have to transform them into char considering 1 or 2 decimal digits based on the starting number, i.e. like this:
n_A = 3.15;
A = sprintf('%.2f',n_A);
n_B = 3.7;
B = sprintf('%.1f',n_B);
My question is how can I apply this:
sprintf('%.2f',#);
or this:
sprintf('%.1f',#);
knowing that the number has one or two digits after the decimal point?
##### 0 comentariosMostrar -2 comentarios más antiguosOcultar -2 comentarios más antiguos

Iniciar sesión para comentar.

### Respuestas (1)

Stephen23 el 11 de Sept. de 2023
Editada: Stephen23 el 11 de Sept. de 2023
You could use another format, e.g.:
fprintf('%.3g\n',[3.15,3.7])
3.15 3.7
##### 2 comentariosMostrar NingunoOcultar Ninguno
Alberto Acri el 11 de Sept. de 2023
Thanks for your answer @Stephen23. The one above is an example.
If I have a number (double) in input (n_A or n_B for example) I want in output a char number that has one or two decimal digits based on the input number.
So,
• if N = 3.15 this becomes '3.15' (char)
• if N = 3.70 this becomes '3.7' (char).
Walter Roberson el 11 de Sept. de 2023
n_A = 3.15;
fprintf('%g\n', n_A);
3.15
n_B = 3.70;
fprintf('%g\n', n_B)
3.7
format long g
n_A
n_A =
3.15
n_B
n_B =
3.7

Iniciar sesión para comentar.

### Categorías

Más información sobre Multirate Signal Processing en Help Center y File Exchange.

R2021b

### Community Treasure Hunt

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

Start Hunting!

Translated by