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

11 次查看(过去 30 天)
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)?

回答(2 个)

Sean de Wolski
Sean de Wolski 2013-11-14
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 2013-11-14
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!

类别

Help CenterFile Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by