PHP — Valor do Real por Extenso

Está função em PHP, transformar o valor monetário para o texto monetário.

function numberToText($value, $uppercase = 0) {
if (strpos($value, ",") > 0) {
$value = str_replace(".", "", $value);
$value = str_replace(",", ".", $value);
}

$singular = ["centavo", "real", "mil", "milhão", "bilhão", "trilhão", "quatrilhão"];
$plural = ["centavos", "reais", "mil", "milhões", "bilhões", "trilhões", "quatrilhões"];

$c = ["", "cem", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"];
$d = ["", "dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"];
$d10 = ["dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezesete", "dezoito", "dezenove"];
$u = ["", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove"];

$z = 0;

$value = number_format($value, 2, ".", ".");
$integer = explode(".", $value);
$cont = count($integer);

for ($i = 0; $i < $cont; $i++)
for ($ii = strlen($integer[$i]); $ii < 3; $ii++)
$integer[$i] = "0" . $integer[$i];

$fim = $cont - ($integer[$cont - 1] > 0 ? 1 : 2);
$rt = '';
for ($i = 0; $i < $cont; $i++) {
$value = $integer[$i];
$rc = (($value > 100) && ($value < 200)) ? "cento" : $c[$value[0]];
$rd = ($value[1] < 2) ? "" : $d[$value[1]];
$ru = ($value > 0) ? (($value[1] == 1) ? $d10[$value[2]] : $u[$value[2]]) : "";

$r = $rc . (($rc && ($rd || $ru)) ? " e " : "") . $rd . (($rd &&
$ru) ? " e " : "") . $ru;
$t = $cont - 1 - $i;
$r .= $r ? " " . ($value > 1 ? $plural[$t] : $singular[$t]) : "";
if ($value == "000"
)
$z++;
elseif ($z > 0)
$z--;
if (($t == 1) && ($z > 0) && ($integer[0] > 0))
$r .= ( ($z > 1) ? " de " : "") . $plural[$t];
if ($r)
$rt = $rt . ((($i > 0) && ($i <= $fim) &&
($integer[0] > 0) && ($z < 1)) ? ( ($i < $fim) ? ", " : " e ") : " ") . $r;
}

return trim($rt ? $rt : "zero");
}

--

--

Software Enginner | Next.js | NestJs | React Native | Flutter | DevOps

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Newerton Vargas de Araujo

Newerton Vargas de Araujo

Software Enginner | Next.js | NestJs | React Native | Flutter | DevOps