Function/method to truncate the fractional part of a number in Matlab
19 次查看(过去 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)?
0 个评论
回答(2 个)
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
0 个评论
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!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!