Quantcast
Channel: User BobbyShaftoe - Stack Overflow
Viewing all articles
Browse latest Browse all 45

Answer by BobbyShaftoe for .NET convert number to string representation (1 to one, 2 to two, etc...)

$
0
0

A conversion from integer to long form English... I could write that ;-) is a pretty good article on the topic:

using System;public class NumberToEnglish {    private static string[] onesMapping =        new string[] {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"        };    private static string[] tensMapping =        new string[] {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"        };    private static string[] groupMapping =        new string[] {"Hundred", "Thousand", "Million", "Billion", "Trillion"        };    private static void Main(string[] args) {        Console.WriteLine(EnglishFromNumber(long.Parse(args[0])));    }    private static string EnglishFromNumber(int number) {        return EnglishFromNumber((long) number);    }    private static string EnglishFromNumber(long number) {        if ( number == 0 ) {            return onesMapping[number];        }        string sign = "Positive";        if ( number < 0 ) {            sign = "Negative";            number = Math.Abs(number);        }        string retVal = null;        int group = 0;        while(number > 0) {            int numberToProcess = (int) (number % 1000);            number = number / 1000;            string groupDescription = ProcessGroup(numberToProcess);            if ( groupDescription != null ) {                if ( group > 0 ) {                    retVal = groupMapping[group] +""+ retVal;                }                retVal = groupDescription +""+ retVal;            }            group++;        }        return sign +""+ retVal;    }    private static string ProcessGroup(int number) {        int tens = number % 100;        int hundreds = number / 100;        string retVal = null;        if ( hundreds > 0 ) {            retVal = onesMapping[hundreds] +""+ groupMapping[0];        }        if ( tens > 0 ) {            if ( tens < 20 ) {                retVal += ((retVal != null) ? "" : "") + onesMapping[tens];            } else {                int ones = tens % 10;                tens = (tens / 10) - 2; // 20's offset                retVal += ((retVal != null) ? "" : "") + tensMapping[tens];                if ( ones > 0 ) {                    retVal += ((retVal != null) ? "" : "") + onesMapping[ones];                }            }        }        return retVal;    }}

Viewing all articles
Browse latest Browse all 45

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>