Get first digit of a number
Monkey Forums/Monkey Programming/Get first digit of a number| 
 | ||
| Maybe I'm too stupid, but I can't get this working. I want to get the first digit of a number, i.e. I have 276 (can have 1 to 6 digits) as int and want to have 2 as the result. What I tried is to convert to string and then take the first character, but local x:int = 276 local a:string = x.ToString() gives me an "expression has no scope" error. What's wrong? Is there an easier way to do it? | 
| 
 | ||
| This is really easy=) One of the options: [monkeycode] Function Main:Int() local x:int = 276 Local a:String = String(x) For Local i:Int=0 Until a.Length Print String.FromChar(a[i]) Next Print "First Number: "+String.FromChar(a[0]) End Function [/monkeycode] | 
| 
 | ||
| The second one: [monkeycode]Function Main:Int() local x:int = 276 Print (x &$4C) Shr 1 Print String.FromChar(IntObject(x).ToString()[0]) End Function [/monkeycode] | 
| 
 | ||
| One using just arithmetic: Method GetFirstDigit:int( val:Int ) Local power:Int = 10 While power < val power *= 10 Wend power /= 10 Return val / power End | 
| 
 | ||
| Let's throw another one on the pile: ' x is an integer. What it the first digit? Local digit% = Abs(x) While digit > 9 digit /= 10 Wend ' digit is now the first digit of x The Abs() is used in case x might be negative. | 
| 
 | ||
| or this: [monkeycode]X%=276 FirstDigit=Int(String(X)[0..1])[/monkeycode] | 
| 
 | ||
| local x:int = 276 local n:int = x Mod 10 | 
| 
 | ||
| @Jesse That grabs the last digit, not the first. | 
| 
 | ||
| Midimaster: That's the exact code snippet I was about to type.  :) | 
| 
 | ||
| ups! Misunderstood. Sorry. | 
| 
 | ||
| Also this: [monkeycode]Function First(digit:Int) Return Int(String(Abs(digit))[0..1]) End[/monkeycode] But Floyd implementatino may be a lot better as it could keep the sign (if the Abs is removed) and it avoids the creation of two strings and the text-to-int conversion. |