Skip to content

Instantly share code, notes, and snippets.

@taai
Created August 13, 2019 14:58
Show Gist options
  • Save taai/8b9b14285612a0a788578bb6fee68163 to your computer and use it in GitHub Desktop.
Save taai/8b9b14285612a0a788578bb6fee68163 to your computer and use it in GitHub Desktop.
Convert number to Latvian words
<?php
function convert_number_to_latvian_words($num)
{
if ( ! is_numeric($num))
return false;
if (($num >= 0 && (int) $num < 0) OR (int) $num < 0 - PHP_INT_MAX) {
// overflow
trigger_error('convert_number_to_latvian_words only accepts numbers between -' . PHP_INT_MAX . ' and ' . PHP_INT_MAX, E_USER_WARNING);
return false;
}
$dict = [
0 => 'nulle',
1 => 'viens',
2 => 'divi',
3 => 'trīs',
4 => 'četri',
5 => 'pieci',
6 => 'seši',
7 => 'septiņi',
8 => 'astoņi',
9 => 'deviņi',
10 => 'desmit',
11 => 'vienpadsmit',
12 => 'divpadsmit',
13 => 'trīspadsmit',
14 => 'četrpadsmit',
15 => 'piecpadsmit',
16 => 'sešpadsmit',
17 => 'septiņpadsmit',
18 => 'astoņpadsmit',
19 => 'deviņpadsmit',
20 => 'divdesmit',
30 => 'trīsdesmit',
40 => 'četrdesmit',
50 => 'piecdesmit',
60 => 'sešdesmit',
70 => 'septiņdesmit',
80 => 'astoņdesmit',
90 => 'deviņdesmit',
100 => 'simts',
1000 => 'tūkstotis',
1000000 => 'miljons',
1000000000 => 'miljards',
];
$pre = [
1 => 'vien',
2 => 'div',
3 => 'trīs',
4 => 'četr',
5 => 'piec',
6 => 'seš',
7 => 'septiņ',
8 => 'astoņ',
9 => 'deviņ',
];
if ($num < 0) {
return 'mīnus '.convert_number_to_latvian_words(abs($num));
}
switch ($num) {
case 0:
case 100:
case 1000:
case 1000000:
case 1000000000:
return $dict[$num];
}
if ($num < 21) {
return $dict[$num];
}
if ($num < 100) {
$x10 = ((int) ($num / 10)) * 10;
$rem = $num % 10;
$str = $dict[$x10];
if ($rem > 0) {
$str .= ' '.$dict[$rem];
}
return $str;
}
if ($num < 1000) {
$x100 = intval($num / 100);
$rem = $num % 100;
$str = ($x100 === 1 ? 'simtu' : $pre[$x100].'simt');
if ($rem > 0) {
$str .= ' '.convert_number_to_latvian_words($rem);
}
return $str;
}
if ($num < 1000000) {
$val = intval($num / 1000);
$rem = $num % 1000;
$str = convert_number_to_latvian_words($val);
$str .= ($val === 1 ? ' tūkstotis' : ' tūkstoši');
if ($rem > 0) {
$str .= ' '.convert_number_to_latvian_words($rem);
}
return $str;
}
throw new Exception('Maximum number that can be converted to words exceeded');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment