Azzera filtri
Azzera filtri

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

11 visualizzazioni (ultimi 30 giorni)
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)?

Risposte (2)

Sean de Wolski
Sean de Wolski il 14 Nov 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 il 14 Nov 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!

Categorie

Scopri di più su Introduction to Installation and Licensing in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by