Search code examples
matlabrounding

How can I cut four numbers after the decimal number without rounding using MATLAB?


I have a number like this:

2.32166873546944

I want to take only four numbers after the decimal point and without rounding, that is, I only want:

2.3216

How do I do this in Matlab ?

I tried several times to get the desired result but I was unable to do so. Please help me....


Solution

  • Using round

    From the documentation (emphasis added),

    Y = round(X) rounds each element of X to the nearest integer. In the case of a tie, where an element has a fractional part of 0.5 (within roundoff error) in decimal, the round function rounds away from zero to the nearest integer with larger magnitude.

    Thus, truncating to n decimal figures can be achieved by reducing the absolute value of the number by 0.5*10^-n and then applying round:

    n = 4;
    x = 2.32166873546944;
    y = round(x-sign(x)*0.5*10^-n, n);
    

    Using fix

    From the documentation (emphasis added),

    Y = fix(X) rounds each element of X to the nearest integer toward zero.

    Thus, it suffices to multiply by 10^n, apply fix, and then divide by 10^n:

    n = 4;
    x = 2.32166873546944;
    y = fix(x*10^n)/10^n;