Borrar filtros
Borrar filtros

Function/method to truncate the fractional part of a number in Matlab

11 visualizaciones (últimos 30 días)
Jeevan Thomas
Jeevan Thomas el 14 de Nov. de 2013
Respondida: Simon el 14 de Nov. de 2013
In C-programming, if I want to truncate and display the decimal places of a number to certain units, I can do that so by giving %x.xf in printf().
For example: float y = 99.0/1000;
To truncate the fractional part to two decimal places, I can write the following statement:
printf("y =%.2f",y);
Can you suggest a similar statement or function in Matlab to realize the same (considering that I want to perform a similar operation to a variable x = 12.34567 truncated to two decimal places)?

Respuestas (2)

Sean de Wolski
Sean de Wolski el 14 de Nov. de 2013
Well, for display purposes you can do it the same way as you do in C by passing a format specifier into fprintf or sprintf
x = 12.34567
fprintf('%.2f\n',x)
However, it's important to note that the variable is a double precision floating point value so this isn't actually truncating the value, it's just changing the display options.
doc fprintf %more info

Simon
Simon el 14 de Nov. de 2013
Hi!
To get the fractional part you may use
fractionalpart = x - floor(x)
Try it with "x=pi" for example. And try it with "x=-pi" as well, you will see that you have to get the fractional part depending on the sign of x!

Categorías

Más información sobre Introduction to Installation and Licensing 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!

Translated by