Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

truncate decimal numbers in matlab?

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.

like image 737
Windy Day Avatar asked Aug 24 '17 02:08

Windy Day


People also ask

How do you truncate to 2 decimal places in MATLAB?

For example, to display exactly 2 decimal digits of pi (and no trailing zeros), use sprintf("%. 2f",pi) .

How do I reduce the number of decimal places in MATLAB?

"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.

How do I truncate in Simulink?

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.


2 Answers

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().

like image 127
jodag Avatar answered Sep 29 '22 09:09

jodag


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)
like image 28
informaton Avatar answered Sep 29 '22 10:09

informaton