Freitag, 2. April 2010

Numbers to german words


#!/bin/sh


exec scala $0 $@


!#


object NumSpeller {


val digits = Array("","ein","zwei","drei","vier","fuenf","sechs","sieben","acht","neun")


val teens = Array("zehn", "elf", "zwoelf", "dreizehn", "vierzehn", "fuenfzehn", "sechzehn", "siebzehn", "achtzehn", "neunzehn")


val tens = Array("", "zehn", "zwanzig", "dreissig", "vierzig", "fuenfzig", "sechzig", "siebzig", "achtzig", "neunzig")


val thousands = Array("", "tausend", "million", "milliarde", "billion", "billiarde", "trillion", "trilliarde")


val thousands2 = Array("", "tausend", "millionen", "milliarden", "billionen", "billiarden", "trillionen", "trilliarden")



def spellGroup(num:Int, factor:Int) = {


val (v3, v2, v1) = ((num / 100) % 10, (num / 10) % 10, num % 10)


val di = v1 match {


case 1 => if (factor >= 2) { "eine" } else if (factor >= 1) { "ein" } else "eins"


case _ => digits(v1)


}



val ts = v2 match {


case 0 => di


case 1 => teens(v1)


case _ => if (v1>0) di + "und" + tens(v2) else tens(v2)


}



val hs = v3 match {


case 0 => ts


case _ => digits(v3) + "hundert" + ts


}



if (v1==1 && v3==0 && v2==0)


hs + thousands(factor)


else


hs + thousands2(factor)


}



def numberGroups(num:Long) = {


def _numberGroups(num:Long, factor:Int):List[(Double,Int)] = factor match {


case 0 => List((num % 1000,0))


case _ => ((num / Math.pow(1000, factor)) % 1000, factor) :: _numberGroups(num, factor - 1)


}


val ints = _numberGroups(num, 6) map (x => (x._1.asInstanceOf[Int],x._2))


//ints filterNot (x => x._1 == 0.0) foreach ( x => printf("(%d,%d)\n",x._1,x._2) )


ints filterNot (x => x._1 == 0.0)


}



def spell(num:Long) = num match {


case 0 => "Null"


case _ => (numberGroups(num) map { x => spellGroup(x._1,x._2) }).mkString.trim


}



}



object n2w {


def main(args:Array[String]) = {


val num = args(0).toLong


printf("%d=%s\n",num,NumSpeller.spell(num))


}


}



n2w.main(args)



Keine Kommentare:

Kommentar veröffentlichen