dolibarr 25.0.0-alpha
functionsnumtoword.lib.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2015 Víctor Ortiz Pérez <victor@accett.com.mx>
4 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
5 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 * or see https://www.gnu.org/
20 */
21
38function dol_convertToWord($num, $langs, $currency = '', $centimes = false)
39{
40 //$num = str_replace(array(',', ' '), '', trim($num)); This should be useless since $num MUST be a php numeric value
41 if (!$num) {
42 return false;
43 }
44
45 // Dedicated converter for French. The generic algorithm below is built on the English
46 // number structure and cannot express French spelling rules (et, hyphens, agreement of
47 // cent/vingt, elision of "un" before cent/mille). See dolConvertToWordFrench().
48 $langcode = $langs->getDefaultLang(0);
49 if (preg_match('/^fr/i', (string) $langcode)) {
50 return dolConvertToWordFrench($num, $langs, $currency, $centimes);
51 }
52
53 $numbackup = $num;
54
55 if (isModEnabled('numberwords')) {
56 $concatWords = $langs->getLabelFromNumber((string) $num, $currency);
57 return $concatWords;
58 } else {
59 $TNum = explode('.', (string) $num);
60
61 $num = abs((int) $TNum[0]);
62 $words = array();
63 $list1 = array(
64 '',
65 $langs->transnoentitiesnoconv('one'),
66 $langs->transnoentitiesnoconv('two'),
67 $langs->transnoentitiesnoconv('three'),
68 $langs->transnoentitiesnoconv('four'),
69 $langs->transnoentitiesnoconv('five'),
70 $langs->transnoentitiesnoconv('six'),
71 $langs->transnoentitiesnoconv('seven'),
72 $langs->transnoentitiesnoconv('eight'),
73 $langs->transnoentitiesnoconv('nine'),
74 $langs->transnoentitiesnoconv('ten'),
75 $langs->transnoentitiesnoconv('eleven'),
76 $langs->transnoentitiesnoconv('twelve'),
77 $langs->transnoentitiesnoconv('thirteen'),
78 $langs->transnoentitiesnoconv('fourteen'),
79 $langs->transnoentitiesnoconv('fifteen'),
80 $langs->transnoentitiesnoconv('sixteen'),
81 $langs->transnoentitiesnoconv('seventeen'),
82 $langs->transnoentitiesnoconv('eighteen'),
83 $langs->transnoentitiesnoconv('nineteen')
84 );
85 $list2 = array(
86 '',
87 $langs->transnoentitiesnoconv('ten'),
88 $langs->transnoentitiesnoconv('twenty'),
89 $langs->transnoentitiesnoconv('thirty'),
90 $langs->transnoentitiesnoconv('forty'),
91 $langs->transnoentitiesnoconv('fifty'),
92 $langs->transnoentitiesnoconv('sixty'),
93 $langs->transnoentitiesnoconv('seventy'),
94 $langs->transnoentitiesnoconv('eighty'),
95 $langs->transnoentitiesnoconv('ninety'),
96 $langs->transnoentitiesnoconv('hundred')
97 );
98 $list3 = array(
99 '',
100 $langs->transnoentitiesnoconv('thousand'),
101 $langs->transnoentitiesnoconv('million'),
102 $langs->transnoentitiesnoconv('billion'),
103 $langs->transnoentitiesnoconv('trillion'),
104 $langs->transnoentitiesnoconv('quadrillion')
105 );
106
107 $num_length = strlen((string) $num);
108 $levels = (int) (($num_length + 2) / 3);
109 $max_length = $levels * 3;
110 $num = substr('00'.$num, -$max_length);
111 $num_levels = str_split($num, 3);
112 $nboflevels = count($num_levels);
113 for ($i = 0; $i < $nboflevels; $i++) {
114 $levels--;
115 $hundreds = (int) ((int) $num_levels[$i] / 100);
116 // No plural 's': "seven hundred", "siebenhundert", "settecento"... (French has its own converter)
117 $hundreds = ($hundreds ? ' '.$list1[$hundreds].' '.$langs->transnoentities('hundred').' ' : '');
118 $tens = (int) ((int) $num_levels[$i] % 100);
119 $singles = '';
120 if ($tens < 20) {
121 $tens = ($tens ? ' '.$list1[$tens].' ' : '');
122 } else {
123 $tsd = (int) ($tens / 10); // tens digit (2-9)
124 $usd = (int) ($tens % 10); // units digit (0-9)
125
126 // French-style systems: 70-79 = sixty + (10-19), 90-99 = eighty + (10-19)
127 // Detection: if the translation of "seventy"/"ninety" contains the word for "ten"
128 $tenWord = trim($list1[10]); // e.g. "dix"
129 if ($usd > 0 && ($tsd == 7 || $tsd == 9) && $tenWord !== '' && strpos(trim($list2[$tsd]), $tenWord) !== false) {
130 // Use the base ten word (60 for 70s, 80 for 90s) + teen word (11-19)
131 $baseWord = trim($list2[$tsd - 1]);
132 // Remove trailing 's' (e.g. quatre-vingts → quatre-vingt when used in composition)
133 if (substr($baseWord, -1) === 's') {
134 $baseWord = substr($baseWord, 0, -1);
135 }
136 $tens = ' '.$baseWord.' ';
137 $singles = ' '.$list1[10 + $usd].' ';
138 } else {
139 $tens = ' '.$list2[$tsd].' ';
140 $singles = ' '.$list1[$usd].' ';
141 }
142 }
143 $words[] = $hundreds.$tens.$singles.(($levels && (int) ($num_levels[$i])) ? ' '.$list3[$levels].' ' : '');
144 } //end for loop
145 $commas = count($words);
146 if ($commas > 1) {
147 $commas -= 1;
148 }
149 $concatWords = implode(' ', $words);
150 // Delete multi whitespaces
151 $concatWords = trim(preg_replace('/[ ]+/', ' ', $concatWords));
152
153 if (!empty($currency)) {
154 $concatWords .= ' '.$currency;
155 }
156
157 // If we need to write cents, spell the 2-digit cents value (e.g. 0.07 => 7 cents, not 70)
158 $tmptab = explode('.', number_format((float) abs($numbackup), 2, '.', ''));
159 $cents = isset($tmptab[1]) ? (int) $tmptab[1] : 0;
160
161 if ($cents > 0) {
162 if (!empty($currency)) {
163 $concatWords .= ' '.$langs->transnoentities('and');
164 }
165
166 $concatWords .= ' '.dol_convertToWord((float) $cents, $langs, '', false);
167 if (!empty($currency)) {
168 $concatWords .= ' '.$langs->transnoentities('centimes');
169 }
170 }
171 return $concatWords;
172 }
173}
174
175
186function dolConvertIntToFrenchWords($n, $reform = false)
187{
188 $n = (int) $n;
189 if ($n < 0) {
190 $n = -$n;
191 }
192 if ($n === 0) {
193 return 'zéro';
194 }
195
196 $sep = $reform ? '-' : ' ';
197 $etjoin = $reform ? '-et-' : ' et ';
198
199 $units = array(
200 'zéro', 'un', 'deux', 'trois', 'quatre', 'cinq', 'six', 'sept', 'huit', 'neuf',
201 'dix', 'onze', 'douze', 'treize', 'quatorze', 'quinze', 'seize',
202 'dix-sept', 'dix-huit', 'dix-neuf'
203 );
204 $tensmap = array(2 => 'vingt', 3 => 'trente', 4 => 'quarante', 5 => 'cinquante', 6 => 'soixante');
205 $scales = array('', 'mille', 'million', 'milliard', 'billion', 'billiard', 'trillion');
206
207 // Spell a number from 1 to 99
208 $below100 = function (int $m) use ($units, $tensmap, $etjoin): string {
209 if ($m < 20) {
210 return $units[$m] ?? '';
211 }
212 $t = intdiv($m, 10);
213 $u = $m % 10;
214 if ($t == 7 || $t == 9) {
215 // 70-79 = soixante + (10..19), 90-99 = quatre-vingt + (10..19)
216 $base = ($t == 7) ? 'soixante' : 'quatre-vingt';
217 if ($t == 7 && $u == 1) {
218 return $base.$etjoin.$units[10 + $u]; // soixante et onze (but quatre-vingt-onze takes no "et")
219 }
220 return $base.'-'.$units[10 + $u];
221 }
222 if ($t == 8) {
223 // 80 = quatre-vingts, 81..89 = quatre-vingt-x (no "s", no "et")
224 return ($u == 0) ? 'quatre-vingts' : 'quatre-vingt-'.$units[$u];
225 }
226 // 20..69
227 $w = $tensmap[$t] ?? '';
228 if ($u == 0) {
229 return $w;
230 }
231 if ($u == 1) {
232 return $w.$etjoin.$units[1]; // vingt et un .. soixante et un
233 }
234 return $w.'-'.$units[$u];
235 };
236
237 // Split into groups of 3 digits, lowest group first (index 0 = units, 1 = thousands, 2 = millions...)
238 $groups = array();
239 $tmp = $n;
240 while ($tmp > 0) {
241 $groups[] = $tmp % 1000;
242 $tmp = intdiv($tmp, 1000);
243 }
244 $ng = count($groups);
245
246 $pieces = array(); // each entry: array('text' => string, 'noun' => bool) ; noun = million/milliard scale
247 for ($g = $ng - 1; $g >= 0; $g--) {
248 $val = $groups[$g];
249 if ($val == 0) {
250 continue;
251 }
252 $h = intdiv($val, 100);
253 $r = $val % 100;
254
255 // "cent" agrees (becomes "cents") only when multiplied and not followed by another numeral:
256 // plural when terminal (units group) or directly before a noun scale (million+),
257 // but invariable before "mille".
258 $centplural = ($h >= 2 && $r == 0 && ($g === 0 || $g >= 2));
259
260 $text = '';
261 if ($h >= 1) {
262 $text = ($h == 1) ? 'cent' : $units[$h].$sep.'cent';
263 if ($centplural) {
264 $text .= 's';
265 }
266 }
267 if ($r > 0) {
268 $rtext = $below100($r);
269 // "quatre-vingts" keeps its "s" only when terminal or before a noun scale, not before "mille".
270 if ($r == 80 && $g === 1) {
271 $rtext = 'quatre-vingt';
272 }
273 $text = ($text === '') ? $rtext : $text.$sep.$rtext;
274 }
275
276 if ($g == 1) {
277 // thousands: "mille" is invariable and takes no leading "un"
278 $text = ($val == 1) ? 'mille' : $text.$sep.'mille';
279 $pieces[] = array('text' => $text, 'noun' => false);
280 } elseif ($g >= 2) {
281 $scaleword = isset($scales[$g]) ? $scales[$g] : '';
282 if ($scaleword !== '') {
283 if ($val >= 2) {
284 $scaleword .= 's'; // millions, milliards...
285 }
286 $text .= ' '.$scaleword; // a noun scale is always separated by a space
287 }
288 $pieces[] = array('text' => $text, 'noun' => true);
289 } else {
290 $pieces[] = array('text' => $text, 'noun' => false);
291 }
292 }
293
294 $result = '';
295 foreach ($pieces as $i => $piece) {
296 if ($i === 0) {
297 $result = $piece['text'];
298 } else {
299 // after a noun scale (million+) keep a space, otherwise use the chosen separator
300 $result .= ($pieces[$i - 1]['noun'] ? ' ' : $sep).$piece['text'];
301 }
302 }
303
304 return $result;
305}
306
307
317function dolConvertToWordFrench($num, $langs, $currency = '', $centimes = false)
318{
319 // Spelling convention, set with constant CONVERT_TO_WORD_FR (Home - Setup - Other setup):
320 // - default/'PRE1990' = traditional spelling (hyphen only between tens and units)
321 // - 'REFORME1990' = 1990 rectified spelling (hyphens between all the numeral words)
322 $reform = (getDolGlobalString('CONVERT_TO_WORD_FR') === 'REFORME1990');
323
324 $numstr = number_format((float) $num, 2, '.', '');
325 $negative = false;
326 if (strpos($numstr, '-') === 0) {
327 $negative = true;
328 $numstr = substr($numstr, 1);
329 }
330 $tmptab = explode('.', $numstr);
331 $intpart = (int) $tmptab[0];
332 $cents = isset($tmptab[1]) ? (int) $tmptab[1] : 0;
333
334 $result = ($intpart === 0) ? '' : dolConvertIntToFrenchWords($intpart, $reform);
335
336 if (!empty($currency)) {
337 if ($result === '') {
338 $result = 'zéro';
339 }
340 $result .= ' '.$currency;
341 }
342
343 if ($cents > 0) {
344 if ($centimes) {
345 $label = $langs->transnoentitiesnoconv($cents === 1 ? 'centime' : 'centimes');
346 $and = $langs->transnoentitiesnoconv('and');
347 $centtext = dolConvertIntToFrenchWords($cents, $reform).' '.$label;
348 if ($result === '') {
349 $result = $centtext;
350 } else {
351 $result .= ' '.$and.' '.$centtext;
352 }
353 } else {
354 // Not an amount: spell the decimal part after "virgule"
355 $result = ($result === '' ? 'zéro' : $result).' virgule '.dolConvertIntToFrenchWords($cents, $reform);
356 }
357 }
358
359 if ($result === '') {
360 $result = 'zéro';
361 }
362 if ($negative) {
363 $result = 'moins '.$result;
364 }
365
366 return $result;
367}
368
369
380function dolNumberToWord($numero, $langs, $numorcurrency = 'number')
381{
382 // If the number is negative convert to positive and return -1 if it is too long
383 if ($numero < 0) {
384 $numero *= -1;
385 }
386 if ($numero >= 1000000000001) {
387 return -1;
388 }
389
390 // Get 2 decimals to cents, another functions round or truncate
391 $strnumber = number_format($numero, 10);
392 $len = strlen($strnumber);
393 $parte_decimal = '00'; // For static analysis, strnumber should contain '.'
394 for ($i = 0; $i < $len; $i++) {
395 if ($strnumber[$i] == '.') {
396 $parte_decimal = $strnumber[$i + 1].$strnumber[$i + 2];
397 break;
398 }
399 }
400
401 /* Dolibarr 3.6.2 doesn't have $langs->default, why ask $lang like a parameter in case it exists? */
402 if (((is_object($langs) && $langs->getDefaultLang(0) == 'es_MX') || (!is_object($langs) && $langs == 'es_MX')) && $numorcurrency == 'currency') {
403 if ($numero >= 1 && $numero < 2) {
404 return ("UN PESO ".$parte_decimal." / 100 M.N.");
405 } elseif ($numero >= 0 && $numero < 1) {
406 return ("CERO PESOS ".$parte_decimal." / 100 M.N.");
407 } elseif ($numero >= 1000000 && $numero < 1000001) {
408 return ("UN MILL&OacuteN DE PESOS ".$parte_decimal." / 100 M.N.");
409 } elseif ($numero >= 1000000000000 && $numero < 1000000000001) {
410 return ("UN BILL&OacuteN DE PESOS ".$parte_decimal." / 100 M.N.");
411 } else {
412 $entexto = "";
413 $number = $numero;
414 if ($number >= 1000000000) {
415 $CdMMillon = (int) ($numero / 100000000000);
416 $numero -= $CdMMillon * 100000000000;
417 $DdMMillon = (int) ($numero / 10000000000);
418 $numero -= $DdMMillon * 10000000000;
419 $UdMMillon = (int) ($numero / 1000000000);
420 $numero -= $UdMMillon * 1000000000;
421 $entexto .= hundreds2text($CdMMillon, $DdMMillon, $UdMMillon);
422 $entexto .= " MIL ";
423 } else {
424 $CdMMillon = 0;
425 $DdMMillon = 0;
426 $UdMMillon = 0;
427 }
428 if ($number >= 1000000) {
429 $CdMILLON = (int) ($numero / 100000000);
430 $numero -= $CdMILLON * 100000000;
431 $DdMILLON = (int) ($numero / 10000000);
432 $numero -= $DdMILLON * 10000000;
433 $udMILLON = (int) ($numero / 1000000);
434 $numero -= $udMILLON * 1000000;
435 $entexto .= hundreds2text($CdMILLON, $DdMILLON, $udMILLON);
436 if (!$CdMMillon && !$DdMMillon && !$UdMMillon && !$CdMILLON && !$DdMILLON && $udMILLON == 1) {
437 $entexto .= " MILL&OacuteN ";
438 } else {
439 $entexto .= " MILLONES ";
440 }
441 }
442
443 if ($number >= 1000) {
444 $cdm = (int) ($numero / 100000);
445 $numero -= $cdm * 100000;
446 $ddm = (int) ($numero / 10000);
447 $numero -= $ddm * 10000;
448 $udm = (int) ($numero / 1000);
449 $numero -= $udm * 1000;
450 $entexto .= hundreds2text($cdm, $ddm, $udm);
451 if ($cdm || $ddm || $udm) {
452 $entexto .= " MIL ";
453 }
454 } else {
455 $ddm = 0;
456 $cdm = 0;
457 $udm = 0;
458 }
459 $c = (int) ($numero / 100);
460 $numero -= $c * 100;
461 $d = (int) ($numero / 10);
462 $u = (int) $numero - $d * 10;
463 $entexto .= hundreds2text($c, $d, $u);
464 if (!$cdm && !$ddm && !$udm && !$c && !$d && !$u && $number > 1000000) {
465 $entexto .= " DE";
466 }
467 $entexto .= " PESOS ".$parte_decimal." / 100 M.N.";
468 }
469 return $entexto;
470 }
471 return -1;
472}
473
482function hundreds2text($hundreds, $tens, $units)
483{
484 if ($hundreds == 1 && $tens == 0 && $units == 0) {
485 return "CIEN";
486 }
487 $centenas = array("CIENTO", "DOSCIENTOS", "TRESCIENTOS", "CUATROCIENTOS", "QUINIENTOS", "SEISCIENTOS", "SETECIENTOS", "OCHOCIENTOS", "NOVECIENTOS");
488 $decenas = array("", "", "TREINTA ", "CUARENTA ", "CINCUENTA ", "SESENTA ", "SETENTA ", "OCHENTA ", "NOVENTA ");
489 $veintis = array("VEINTE", "VEINTIUN", "VEINTID&OacuteS", "VEINTITR&EacuteS", "VEINTICUATRO", "VEINTICINCO", "VEINTIS&EacuteIS", "VEINTISIETE", "VEINTIOCHO", "VEINTINUEVE");
490 $diecis = array("DIEZ", "ONCE", "DOCE", "TRECE", "CATORCE", "QUINCE", "DIECIS&EacuteIS", "DIECISIETE", "DIECIOCHO", "DIECINUEVE");
491 $unidades = array("UN", "DOS", "TRES", "CUATRO", "CINCO", "SEIS", "SIETE", "OCHO", "NUEVE");
492 $entexto = "";
493 if ($hundreds != 0) {
494 $entexto .= $centenas[$hundreds - 1];
495 }
496 if ($tens > 2) {
497 if ($hundreds != 0) {
498 $entexto .= " ";
499 }
500 $entexto .= $decenas[$tens - 1];
501 if ($units != 0) {
502 $entexto .= " Y ";
503 $entexto .= $unidades[$units - 1];
504 }
505 return $entexto;
506 } elseif ($tens == 2) {
507 if ($hundreds != 0) {
508 $entexto .= " ";
509 }
510 $entexto .= " ".$veintis[$units];
511 return $entexto;
512 } elseif ($tens == 1) {
513 if ($hundreds != 0) {
514 $entexto .= " ";
515 }
516 $entexto .= $diecis[$units];
517 return $entexto;
518 }
519 if ($units != 0) {
520 if ($hundreds != 0 || $tens != 0) {
521 $entexto .= " ";
522 }
523 $entexto .= $unidades[$units - 1];
524 }
525 return $entexto;
526}
$c
Definition line.php:353
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dolConvertToWordFrench($num, $langs, $currency='', $centimes=false)
Convert a number into French words.
dol_convertToWord($num, $langs, $currency='', $centimes=false)
Function to return a number into a text.
hundreds2text($hundreds, $tens, $units)
hundreds2text
dolConvertIntToFrenchWords($n, $reform=false)
Convert a non-negative integer into French words (standard French: soixante-dix, quatre-vingts,...
dolNumberToWord($numero, $langs, $numorcurrency='number')
Function to return number or amount in text.