Is there a quick and easy way to truncate a decimal number, say beyond 4 digits, in MATLAB?
round()
isn't helping, it's still rounding off. I have to use it in for loop, so the quickest way is appreciated.
Thanks for your inputs.
For example, to display exactly 2 decimal digits of pi (and no trailing zeros), use sprintf("%. 2f",pi) .
"format short g" will show up to 4 decimal places, dropping trailing 0's from the display. None of the "format" commands allow you to select the number of decimal places to display.
Specify the column length of the output. If the specified column length is longer than the input column length, the block pads the columns. If the specified column length is shorter than the input column length, the block truncates the columns.
Here's one method to truncate d
digits after the decimal.
val = 1.234567;
d = 4;
val_trunc = fix(val*10^d)/10^d
Result
val_trunc =
1.2345
If you know that val
is positive then floor()
will work in place of fix()
.
Yet another option:
x = -3.141592653;
x_trun = x - rem(x,0.0001)
x_trun =
-3.1415
Kudos to gnovice for the update.
In general, for n
decimal places:
x_trun = x - rem(x,10^-n)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With