Shop OBEX P1 Docs P2 Docs Learn Events
separating individual digits of decimal number — Parallax Forums

separating individual digits of decimal number

msiriwardenamsiriwardena Posts: 301
edited 2014-03-23 08:11 in Propeller 1
What I would like achieve is to separate the individual numerals of a decimal number.

Like variable x value = 1234
the individual numerals 1,2,3,4 in different variables.

example : to place 1 in a variable a, 2 in a variable b and 3 in a variable 3 etc.

Thank you.

Siri

Comments

  • Mark_TMark_T Posts: 1,981
    edited 2014-03-21 18:26
    In Spin I presume? Or PASM?

    Anyway in spin you can split a number into the last digit and the rest with / and // operators -
      repeat
        digit := value // 10
        value /= 10
      until value == 0
    
    or something like that - the remainder gives the last digit, then divide by ten and repeat - unfortunately
    that yields them in the wrong order for most uses. If you are only interested in, say, 3 digits its easy
    to pick them out:
      hundreds := value / 100
      tens := value / 10 // 10
      units := value // 10
    
  • kwinnkwinn Posts: 8,697
    edited 2014-03-21 18:32
    I was going to suggest what Mark posted as well as using one of the binary to ascii methods and then masking off all but the 4lsb's. Of course if you wanted to print or display the actual digits masking would not be needed.
  • msiriwardenamsiriwardena Posts: 301
    edited 2014-03-22 08:19
    @Mark_T,@Kwinn

    Thanks for you help.I was looking at the code from a clock and then I thought may be there are better ways.

    Thanks again for the quick answers.

    Siri
  • JonnyMacJonnyMac Posts: 9,107
    edited 2014-03-22 21:21
    You could always write a method to simplify digit extraction from any position:
    pub dig(value, pos)
    
    '' Returns digit from pos (0..9) of value
    
      if ((pos < 0) or (pos > 9))
        return 0
      
      repeat pos
        value /= 10
        
      return ||value // 10
    
  • msiriwardenamsiriwardena Posts: 301
    edited 2014-03-23 08:11
    @JonnyMac
    Thanks for the code snippet.Looks very elegant.Will give it a try.


    Siri
Sign In or Register to comment.