View Full Version : KB MB division decimal point

sonny

10-22-2012, 09:13 PM

Hi

Trying to do some simple division with KB

to get something like 0.5 megabyte

$sum = round(500.30 / 1024, 2);

echo $sum;

best round gives me is 0.49

Thanks

Sonny

Fou-Lu

10-22-2012, 09:46 PM

Which is correct though. The numbers you have are ~0.48857, which rounded to two decimal points is 0.49. If you want 0.5, you round to 1 decimal point, but that means ever calculation will round to the nearest 1/10th instead of 1/100th.

patryk

10-22-2012, 09:49 PM

http://php.net/manual/en/function.round.php

set number of decimal places to 1 and you'll get 0.5

sonny

10-22-2012, 09:53 PM

Fou-Lu

How do you display lets say 0.7 mb?

I messed with floor and others but could

not get it.

If I set round to 1 decimal, it will just just

round up to one mb. floor will round down

to 0 mb

Sonny

patryk

10-22-2012, 10:47 PM

round(0.732131312, 1) will return 0.7

that's how it works. also there are flags you can set as third argument if you want other type of rounding.

check link i've posted above for details

sonny

10-23-2012, 01:15 AM

round(0.732131312, 1) will return 0.7

that's how it works. also there are flags you can set as third argument if you want other type of rounding.

check link i've posted above for details

Hi

I know that, but from 973.0 up it will show 1MB,

problem is 1MB = 1024, so I am trying to

round down to 0.9 in this case.

I guess I could do some IF between 973 -1024

and use 2 decimals. just thought I could do that

with some rounding function directly.

Thanks

Sonny

Fou-Lu

10-23-2012, 01:43 AM

You have to choose between using a printformatter, rounding, or casting. You cannot have the best of both worlds unless you want to start handling on steps of 512 instead of 1024.

Using a printf will truncate off the remaining digits. But that means your 500.30 would result in 0.49. Rounding will make 500.30 into 0.5, but will convert 0.99 to 1.0. You need to choose.

Or of course you can simply write something that shows < 1024KB as a KB rating, and handle it from there. Then you'd see 500.30KB, and at 1033KB you'd see 1.01MB. Easiest done if you measure in a non-multiple unit (bytes). Writing a function like this would be trivial.

Powered by vBulletin® Version 4.2.2 Copyright © 2018 vBulletin Solutions, Inc. All rights reserved.