Get first digit of a number

Monkey Forums/Monkey Programming/Get first digit of a number

Yoda(Posted 2012) [#1]
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?


vbnz(Posted 2012) [#2]
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]


vbnz(Posted 2012) [#3]
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]


Gerry Quinn(Posted 2012) [#4]
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



Floyd(Posted 2012) [#5]
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.


Midimaster(Posted 2012) [#6]
or this:

[monkeycode]X%=276
FirstDigit=Int(String(X)[0..1])[/monkeycode]


Jesse(Posted 2012) [#7]
local x:int = 276
local n:int  = x Mod 10



Goodlookinguy(Posted 2012) [#8]
@Jesse

That grabs the last digit, not the first.


Samah(Posted 2012) [#9]
Midimaster: That's the exact code snippet I was about to type. :)


Jesse(Posted 2012) [#10]
ups! Misunderstood.

Sorry.


ziggy(Posted 2012) [#11]
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.