I need two decimal values without rounding off
Ältere Kommentare anzeigen
Hi, I have a matrix which do contain decimal values.But I need just 2 decimals without rounding off the values.For example I have a value like 0.0194.My result should be 0.01.How can I do that?
Antworten (2)
madhan ravi
am 22 Jul. 2018
Bearbeitet: madhan ravi
am 23 Jul. 2018
Hi try this:
a=floor(100 * 0.0194)/100
fprintf('%0.2f',a)
For more clarification click the link below:
https://www.mathworks.com/matlabcentral/answers/32169-how-can-i-format-a-percent-using-2-digits-after-the-decimal
Note:floor command was taken from Sir Walter.
I recently figured out a syntax you were looking for. Try this for sure:
format bank
6 Kommentare
Walter Roberson
am 23 Jul. 2018
>> f = 0.0194
f =
0.0194
>> format bank
>> f
f =
0.02
format bank rounds; the user does not want to round.
madhan ravi
am 23 Jul. 2018
Oh thank you sir walter then I think the first option would be fine I guess? Am I correct or?
Walter Roberson
am 23 Jul. 2018
The user did not specify what they wanted done for negative values.
It is not clear what the user wants to do with the value, whether they want to use it in further calculation or want to display it or create it as a character vector. If they do want to use it for further calculation, I hope they take into account that there is no way to exactly represent most multiples of 1/100 in binary floating point.
madhan ravi
am 23 Jul. 2018
Yes sir walter I understand your point. Could you please answer my question regarding subs?
Image Analyst
am 24 Jul. 2018
You mean the question about the first option being fine? Yes of course it would work - it's basically the answer I gave, before you realized your first answer with sprintf() (which gave 0.02) didn't work and changed it. And then Walter added the option of floor, which handles the rounding in a different direction for negative numbers. So, yes fix() and floor() both can work - just depends on what they want. If there are no negative numbers, it doesn't matter and you can use either fix() or floor().
"format bank" just changes how the numbers are displayed but does not actually change the number at all like fix/floor does.
Walter's last sentence is also important to understand, as is this related FAQ: https://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
madhan ravi
am 24 Jul. 2018
Thank you for the information sir.
Image Analyst
am 22 Jul. 2018
Use fix:
v = 0.0194
v2 = fix(100 * v)/100
1 Kommentar
Walter Roberson
am 22 Jul. 2018
If your value were -0.0194 and you want the answer -0.01 then fix() is the right thing to use. If you wanted -0.02 instead (the 1/100th that is less than or equal to the number) then you would use floor() instead of fix()
Kategorien
Mehr zu Logical finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!