I’m trying to make a percentage progress bar for an XMMS web interface,
I want to take the total track time and the elapsed time and then make
a length for the bar from the percentage completed.
something like:
totalbarsize = 180
timeelapsed = 10
totaltime = 30
percomplete = 0.0
barlength = 0.0
percomplete = timeelapsed / totaltime
barlength = totalbarsize*percomplete
puts barlength
Now that should give me a barlength of 60 pixels but it gives 0
instead. Anyone know what I’m doing wrong?
Thanks!
(I’ll forget that I need barlength as an integer rather than a float
for now :-P)
jamiethehutt wrote:
percomplete = 0.0
Thanks!
(I’ll forget that I need barlength as an integer rather than a float
for now :-P)
timeelapsed and totaltime are Integers. So when you divide them, it does
integer division:
irb(main):001:0> 10/30
=> 0
irb(main):002:0> 10.0 / 30.0
=> 0.333333333333333
try
percomplete = timeelapsed.to_f / totaltime
or
percomplete = timeelapsed / totaltime.to_f
or
percomplete = timeelapsed.to_f / totaltime.to_f
or
totaltime = 30.0
timeelapsed = 10.0
You get the idea
Floats for floating point division.
-Justin
Division of 2 integers results in an integer. So, try setting
timeelapsed to 10.0 instead of 10.
Tim
jamiethehutt wrote:
…
puts barlength
You need Floats all the way down.
The division of Fixnum values ( timeelapsed / totaltime)
produces a Fixnum value, which is 0 as 0.333 gets truncated
put a .0 after all the non-Float values to force them to be Float
“jamiethehutt” [email protected] writes:
percomplete = 0.0
barlength = 0.0
percomplete = timeelapsed / totaltime
This is an integer-division, and since totaltime is always bigger than
timeelapsed (in theory
it is always 0.
You could try defining totaltime as 30.0 initially or write it as
percomplete = timeelapsed.to_f / totaltime
or something.
barlength = totalbarsize*percomplete
puts barlength
Now that should give me a barlength of 60 pixels but it gives 0
instead. Anyone know what I’m doing wrong?
Thanks!
Tom
ChrisH wrote:
barlength = totalbarsize*percomplete
puts barlength
You need Floats all the way down.
The division of Fixnum values ( timeelapsed / totaltime)
produces a Fixnum value, which is 0 as 0.333 gets truncated
put a .0 after all the non-Float values to force them to be Float
Fogot to say, to get an Integer (or Fixnum id Ruby parlance) just call
to_i on the Float value to covert by truncating the value.
cheers
Use quo. For example:
percomplete = timeelapsed.quo(totaltime) => 0.333333333333333
Regards, Morton