-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumToEng.cs
More file actions
89 lines (78 loc) · 2.1 KB
/
NumToEng.cs
File metadata and controls
89 lines (78 loc) · 2.1 KB
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
using System;
using System.Collections.Generic;
namespace ddate
{
class NumToEng
{
private static readonly string[] Ones = { null, "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine" };
private static readonly string[] Teens = { "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
private static readonly string[] Tens = {null, null, "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
private static readonly string[] BigNumbers = {"Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion" };
public static string ToEnglishWords(long number, bool useDash = true)
{
if (number == 0) return "Zero";
var words = new List<string>();
bool isNegative = number < 0;
GetOnesToHundreds(number, words);
for (int ii = 1; ii <= BigNumbers.Length; ii++)
{
long pow = number / PowTen(ii*3);
if (pow < 1) break;
words.Add(BigNumbers[ii - 1]);
GetOnesToHundreds(pow, words);
}
words.RemoveAll(x => x == null);
words.Reverse();
return (isNegative ? "Negative " : null) + String.Join(useDash ? "-" : " ", words);
}
public static string ToRankedNumeric(int number)
{
return number + GetRankSuffix(number);
}
private static long PowTen(long x)
{
long y = 10;
for (int ii = 1; ii < x; ii++)
y *= 10;
return y;
}
private static void GetOnesToHundreds(long number, List<string> words)
{
if (number == 0) return;
number = Math.Abs(number);
var ones = number%10;
var tens = (number/10)%10;
var hundreds = (number/100)%10;
if (tens == 1)
{
words.Add(Teens[ones]);
}
else
{
words.Add(Ones[ones]);
words.Add(Tens[tens]);
}
if (hundreds != 0)
{
words.Add("Hundred");
words.Add(Ones[hundreds]);
}
}
private static string GetRankSuffix(int number)
{
if ((Math.Abs(number) / 10) % 10 == 1)
return "th";
switch (Math.Abs(number) % 10)
{
case 1:
return "st";
case 2:
return "nd";
case 3:
return "rd";
default:
return "th";
}
}
}
}