Literally convert decimal to string
18 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ganesh Gebhard
el 24 de Abr. de 2021
Respondida: Jan
el 26 de Abr. de 2021
Hey!
I hope I have a simple question, I just couldn't figure it out.
I have several numbers which I want to be converted to string quite literally:
12.000 -> '12.000'
4.0 -> '4.0'
34.760000 -> '34.760000'
As you can see, I cannot simply pad zeros, since that highly depends on how many zero are given with the number.
Does anyone know how to do this?
8 comentarios
Scott MacKenzie
el 26 de Abr. de 2021
Editada: Scott MacKenzie
el 26 de Abr. de 2021
Is the idea to replicate MATLAB's format for numbers appearing the command window? In this case, here's an idea that might help (but requires R2021a). Use fmt = format to get the current display format. fmt is a DisplayFormatOptions object. Query the DisplayFormatOptions object and respond accordingly:
format short
x = 5/4
fmt = format;
fmt.NumericFormat
% "short", therefore 4 digits after decimal point
format long
x
fmt = format;
fmt.NumericFormat
% "long", therefore 15 digits after decimal point
Output:
x =
1.2500
ans =
"short"
x =
1.250000000000000
ans =
"long"
Respuesta aceptada
Jan
el 26 de Abr. de 2021
If the values are stored as floating point numbers in double or single format, they do not have trailing zeros. Trailing zeros after the decimal point are not defined mathematically, as well as leading zeros before the point.
So if you reall have a 12.000 anywhere, this is either a char vector or string, or this comes from choosing a specific output format:
x = 12
format long
x
format shortEng
x
% Or explicitly:
fprintf('%d\n', x)
fprintf('%f\n', x)
fprintf('%.3f\n', x)
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Productos
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!