forked from soaresbest/extenso
/
NumeroExtenso.cs
98 lines (76 loc) · 2.69 KB
/
NumeroExtenso.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Extenso
{
public static class NumeroExtenso
{
public static string Converter(string numero)
{
var regex = new Regex(@"^\d+$");
bool isMatch = regex.IsMatch(numero);
if (!isMatch)
{
throw new ArgumentException(string.Format("o numero {0} não é numeral", numero), "numero");
}
var stringBuilder = new StringBuilder();
numero = numero.TrimStart('0');
List<Bloco> blocos = FabricaBlocos.GerarBlocos(numero);
if (numero == string.Empty)
{
return "zero";
}
if (numero == "1000")
{
return "mil";
}
foreach (Bloco bloco in blocos)
{
string sufixo = ClasseNumerica.SufixoDe(bloco);
if (sufixo == string.Empty && bloco.Ordem > 1)
{
continue;
}
stringBuilder.Append(ColocarSeparadorDeCentena(bloco, blocos));
stringBuilder.Append(bloco.Centena);
if (sufixo != string.Empty)
{
stringBuilder.Append(" ");
stringBuilder.Append(sufixo);
}
}
return stringBuilder.ToString();
}
private static string ColocarSeparadorDeCentena(Bloco bloco, List<Bloco> blocos)
{
int indexOf = blocos.IndexOf(bloco);
bool jaEstaPreenchido = indexOf > 0;
bool proximasCentenasZeradas = ProximasCentenasZeradas(blocos, indexOf);
if (bloco.Centena.ToInt() == 0)
{
return string.Empty;
}
if (proximasCentenasZeradas && jaEstaPreenchido)
{
return " e ";
}
bool temDezenaZerada = bloco.Centena.Dezena.ToInt() == 0;
bool centenaMenorQueCem = bloco.Centena.ToInt() < 100;
if (jaEstaPreenchido && (temDezenaZerada || centenaMenorQueCem))
{
return ", ";
}
return string.Empty;
}
private static bool ProximasCentenasZeradas(List<Bloco> blocos, int indexOf)
{
int somaCentenas = 0;
for (int i = indexOf + 1; i < blocos.Count; i++)
{
somaCentenas += blocos[i].Centena.ToInt();
}
return somaCentenas == 0;
}
}
}