how can i take a variable which store decimal values

7 vues (au cours des 30 derniers jours)
Mukul Khandelwal
Mukul Khandelwal le 24 Déc 2015
Commenté : John D'Errico le 22 Jan 2024
I am having problem to store decimal value. whenever i am taking greater denominator value it shows only zero . please can any one help me asap
  1 commentaire
dpb
dpb le 24 Déc 2015
Well, from just the description we don't know precisely what operation you mean by "[I} am taking greater denominator value". Show us code and input.

Connectez-vous pour commenter.

Réponses (1)

Walter Roberson
Walter Roberson le 25 Déc 2015
If you have variables A, B, that are members of one of the integer classes, such as uint8 or int16, then when you divide A/B the result is defined to be the same as
cast(double(A)/double(B), class(A))
That is, a fraction will be calculated but the result will be made back into the original data type. The process of converting a floating point value to an integer data type is defined to be done by rounding. uint8(159.3) rounds to uint8(159), uint8(159.6) rounds to uint8(160) .
Therefore if you have two integer variables, A/B and B > A, then the result will come out as either 0 or 1 depending on which way the fraction double(A)/double(B) rounds. In particular for A/B with B from A up to and including 2*A will round to 1, and A/B with B > 2*A will round to 0.
If this is a problem then you should either not be using integer class variables or you should be converting the values to double before doing the division, double(A)/double(B) so that the result is not converted back to class(A).
Note: It isn't exactly class(A) that is used in practice but it only makes a difference if you start mixing double and integer class in an operation.
  2 commentaires
Madhu
Madhu le 22 Jan 2024
Déplacé(e) : John D'Errico le 22 Jan 2024
x = 195
fd = 2
y = x./fd
i am getting the value as 98
but i need the value as decimal as 97.2
what can i do/
please anyone help me
John D'Errico
John D'Errico le 22 Jan 2024
your number is an INTEGER. Dividing it by 2 yields another integer.
x = uint8(195)
x = uint8 195
y = x/2
y = uint8 98
class(y)
ans = 'uint8'
You need to convert it to a double FIRST.
z = double(x)/2
z = 97.5000

Connectez-vous pour commenter.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by