Effacer les filtres
Effacer les filtres

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

11 vues (au cours des 30 derniers jours)
Jeevan Thomas
Jeevan Thomas le 14 Nov 2013
Réponse apportée : Simon le 14 Nov 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)?

Réponses (2)

Sean de Wolski
Sean de Wolski le 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 le 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!

Catégories

En savoir plus sur Introduction to Installation and Licensing dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by