How to truncate all the decimal places??
42 views (last 30 days)
I am working on a code that loops over time and have been told that I am at this time "rounding the time to the nearest whole number. This is wrong. You need to truncate all the decimal places." I am unsure exactly what this means and how to implement so any would be appreciated. A relevant extract of my code is below;
dt=0.01; %Define time step
diagstep=10; %diagnostic time step
if (round(time/diagstep * diagstep) == time)
[xcounter] = ParticleCounterFun(x0, particleno)
%%xcounter function file is;
function [ xcounter ] = ParticleCounterFun( x0, particleno )
%Initialise counters used in E field diagnostics
if (0<=x0(np) & x0(np)<1)
if (1<=x0(np) & x0(np)<2)
if (2<=x0(np) & x0(np)<3)
if (3<=x0(np) & x0(np)<4)
if (4<=x0(np) & x0(np)<5)
xcounter=[counter01 counter12 counter23 counter34 counter45]
It is in the condition for the IF statement that i must 'truncate all decimal places' and not just round to nearest whole number so if anyone could help me on this!
Iain on 25 Feb 2014
fix(time) rounds time towards 0, so it gets rid of the decimal places. (truncates numerically)
str = num2str(time); truncated = str(1); this takes the 1st character when the number is expressed as a string (truncates textually - you will need to change this to do it properly)
It looks like you wanted to round to something other than the nearest integer, but got it wrong: If you want rid of all but the 1st decimal place, then you want, fix(time*10)/10 if you want rounded down to the nearest 10, fix(time/10)*10.
Dishant Arora on 25 Feb 2014
cast your variable to int16/32/64 depending upon your requirement.
Gabor on 16 Aug 2021
Edited: Gabor on 16 Aug 2021
fix(1.12) -> remove decimals -> result: 1
fix(23.858457) -> remove decimals -> result: 23
For datetime comparison:
datenum(datetime('now','Format','d-MMM-y')) -> 738385.03
fix(datenum(datetime('now','Format','d-MMM-y'))) -> 738385.00
Took me 20 minutes to find the answer to this simple question, I hope I saved some time for you!