开发者

Is there a way in .Net to get a string value for an int's word?

开发者 https://www.devze.com 2022-12-25 13:42 出处:网络
For example: (1).SomeFunction().Equals(\"one\") (2).SomeFunction().Equals(\"two\") I really only need it for digits 1-9 in the case I\'m working with, should I just use a switch/select case?

For example:

(1).SomeFunction().Equals("one")
(2).SomeFunction().Equals("two")

I really only need it for digits 1-9 in the case I'm working with, should I just use a switch/select case?

Update I won't need localization in this case either.

Update 2 Here's what I ended up using:

Private Enum EnglishDigit As Integer
    zero
    one
    two
    three
    four
    five
    s开发者_高级运维ix
    seven
    eight
    nine
End Enum

(CType(someIntThatIsLessThanTen, EnglishDigit)).ToString()


How about an enumeration?

enum Number
{
    One = 1, // default value for first enum element is 0, so we set = 1 here
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
}

Then you can type things like...

((Number)1).ToString()

If you need localization then you can add a DescriptionAttribute to each enum value. The attribute's Description property would store the name of the resourse item's key.

enum Number
{
    [Description("NumberName_1")]
    One = 1, // default value for first enum element is 0, so we set = 1 here 

    [Description("NumberName_2")]
    Two,

    // and so on...
}

The following function will grab the value of the Description property from the attribute

public static string GetDescription(object value)
{
    DescriptionAttribute[] attributes = null;
    System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
    if (fi != null)
    {
        attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    }

    string description = null;
    if ((attributes != null) && (attributes.Length > 0))
    {
        description = attributes[0].Description;
    }

    return description;
}

This can be called in the following manner:

GetDescription(((Number)1))

From that you can then pull the relevant value from the resource file, or just call .ToString() if null was returned.

Edit

Various commenters have pointed out (and I have to agree) that it would be simpler to just use the enum value names to reference localised strings.


create a dictionary of strings:

string[] digits = new string[] 
{
   "zero",
   "one",
   "two",
   ...
};

string word = digits[digit];


Use a lookup table; an array will do. It's no slower than an enum, and it's easier to localize.

edit

Andrey's code sample is what I was suggesting, although I think calling it a dictionary is a bit confusing.


If you don't need localization, I'd suggest Richard Ev's solution. For localization, however, I'd suggest adding the ten digit names to a resource file, for example NumberName_0 to NumberName_9. This way, when looking up a number, you can just load the resource with the name String.Format("NumberName_{0}", mydigit).

The same technique, by the way, also works fine for localizable enumeration names or descriptions.


Why stop at 1-9...

C#'s version of the way Squeak Smalltalk does it for all numbers to a vigintillion:

    public static String AsWords(this int aNumber) {
        var answer = "";
        if (aNumber == 0) return "zero";
        if (aNumber < 0) {
            answer = "negative";
            aNumber = Math.Abs(aNumber);
        }

        var thousands = new[] {"", "thousand", "million", "billion", "trillion", "quadrillion", "quintillion", "sextillion", "septillion","octillion", "nonillion", "decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion", "quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion", "vigintillion"};
        var thousandCount = 0;
        while (aNumber > 0) {
            var underOneThousandName = ThreeDigitName(aNumber % 1000);
            aNumber = aNumber / 1000;
            if(underOneThousandName != "") {
                if (answer != "") answer = "," + answer;
                answer = underOneThousandName + " " + thousands[thousandCount] + answer;
            }
            thousandCount += 1;
        }
        return answer;
    }

    private static string ThreeDigitName(int aNumberLessThanOneThousand) {
        if (aNumberLessThanOneThousand == 0) return "";
        var units = new[] {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eightteen", "nineteen"};
        var answer = "";
        if (aNumberLessThanOneThousand > 99) {
            answer = units[(aNumberLessThanOneThousand / 100) - 1] + " hundred";
            if (aNumberLessThanOneThousand % 100 != 0)
                answer += " " + ThreeDigitName(aNumberLessThanOneThousand % 100);
            return answer;
        }
        if (aNumberLessThanOneThousand < 20) return units[aNumberLessThanOneThousand -1];
        var multiplesOfTen = new[] {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
        answer += multiplesOfTen[(aNumberLessThanOneThousand / 10)-2];
        if (aNumberLessThanOneThousand % 10 != 0) answer += "-" + units[(aNumberLessThanOneThousand % 10)-1];
        return answer;
    }


I don't think there are any built-in functions to do this. I would use select case.


If you are using 2008:

public static String AsWord(this int aNumber) {
    return ((Number) aNumber).ToString();
}

enum Number {
    One = 1,
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号