how to round of a number into 2 decimals places without using the round function?

Antworten (1)

Rik
Rik am 2 Mai 2019

0 Stimmen

Why not use the round function?
You could use floor, ceil, or fix instead, but that would be cheating a bit.
Anyway, you can use the code below:
rounded_value=str2double(sprintf('%.2f',value));

3 Kommentare

Lucy Hannah
Lucy Hannah am 2 Mai 2019
no i mean for example i have 3.1425. I want to round it of into 3.14 only, if i use floor(a*100)/100 it will become 3.1400
Adam
Adam am 2 Mai 2019
floor( 3.1425 * 100 ) / 100
works fine for me. But then I would always just use the round function anyway since that is precisely what it is there for!
Stephen23
Stephen23 am 2 Mai 2019
Bearbeitet: Stephen23 am 2 Mai 2019
"...if i use floor(a*100)/100 it will become 3.1400"
How numbers are displayed is controlled by the format command, where the default setting is short. You can change the format setting and you might get what you want:
>> format short g
>> floor(3.1425*100)/100
ans = 3.14
It is also important to note that this numeric value does not actually exist: what you see displayed is only an approximation of the binary floating point number that is actually stored in memory. Remember, how data is displayed is a totally different thing to how it is stored in memory!

Melden Sie sich an, um zu kommentieren.

Tags

Gefragt:

am 2 Mai 2019

Bearbeitet:

am 2 Mai 2019

Community Treasure Hunt

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

Start Hunting!

Translated by