Shop OBEX P1 Docs P2 Docs Learn Events
Float Variables? — Parallax Forums

Float Variables?

propwellpropwell Posts: 87
edited 2009-02-05 01:05 in Propeller 1
Hi there,

i hope i'm not annoying you with such a stupid question, but i'm trying to solve it since several hours, ans still can't find any solution.

My Problem is:
if got a code like this:
repeat i from 0 to 50
  { do somethin with i }
  stat := i/50*100
  gr.textmode(3,3,6,5)     
  gr.text(0, -50, num.ToStr( stat , Num#DEC ))




so i want to print the percentage of how far my repeat-function has come.
But i can't find any solution on how to deal with this float-expression...

Can you please help me?

Thanks a lot!

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2009-02-04 19:58
    Other than in constant expressions, there's no support for floating point in Spin.· There is a floating point library downloadable from the Propeller Object Exchange that provides floating point operations as function calls and another object in the Exchange for floating point output ("FloatString").· Download them and look at the documentation that's included.

    You can use scaled integers for your program.· For example, you could calculate "stat" in percent like this:

    stat := (i *100) / 50

    This gives you an integer from 0 to 100 for values of i from 0 to 50.· In this particular case, you could just use i * 2 for your percent.

    ·
  • propwellpropwell Posts: 87
    edited 2009-02-04 20:10
    hey thank you very much for your fast answer! i'll try this library, but your hint did it! thank you very much!
  • JasonDorieJasonDorie Posts: 1,930
    edited 2009-02-05 01:05
    In general, it's a good idea to avoid floating point math if you can do something with integers (like Mike's excellent example here). Integer math will always be MUCH faster than the floating point (decimal) version, and will be guaranteed to be as precise as you choose.

    If you were looping over 624 things, you would do this:
    NumThings := 624
    repeat i from 0 to (NumThings-1)
      stat := (i * 100) / NumThings
    
    

    ...and if you wanted 10ths of a percent, you'd do this:
    NumThings := 624
    repeat i from 0 to (NumThings-1)
      stat := (i * 1000) / NumThings
    

    ...in which case your answer would range from 0 to 1000 instead of 0 to 100. This is called 'fixed point' math, since you're representing a decimal point by just maintaining your numbers with a constant scaling factor multiplied in.

    Jason
Sign In or Register to comment.