3

I'm trying to figure out if there is an easy way to convert numbers into words take 9 and convert it to nine.

user1800738
  • 167
  • 2
  • 9
  • No, there is no built-in way to do this in PowerShell. You'll have to write your own function to do so. – Ken White Oct 31 '14 at 20:06

2 Answers2

4

There is an excellent library for .NET called Humanizer that can do exactly this. I haven't tried this yet, but it looks like there is a PowerShell wrapper for it. I suspect this will do exactly what you need.

KevinD
  • 3,023
  • 2
  • 22
  • 26
0

This has been asked about .NET/C#; you could put this in a class and use Add-Type in powershell to make this work.

.NET convert number to string representation (1 to one, 2 to two, etc...)

Maybe something like this (untested):

$class = @"
    public class Num2Word
    {
        public static string NumberToText( int n)
          {
           if ( n < 0 )
              return "Minus " + NumberToText(-n);
           else if ( n == 0 )
              return "";
           else if ( n <= 19 )
              return new string[] {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", 
                 "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", 
                 "Seventeen", "Eighteen", "Nineteen"}[n-1] + " ";
           else if ( n <= 99 )
              return new string[] {"Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", 
                 "Eighty", "Ninety"}[n / 10 - 2] + " " + NumberToText(n % 10);
           else if ( n <= 199 )
              return "One Hundred " + NumberToText(n % 100);
           else if ( n <= 999 )
              return NumberToText(n / 100) + "Hundreds " + NumberToText(n % 100);
           else if ( n <= 1999 )
              return "One Thousand " + NumberToText(n % 1000);
           else if ( n <= 999999 )
              return NumberToText(n / 1000) + "Thousands " + NumberToText(n % 1000);
           else if ( n <= 1999999 )
              return "One Million " + NumberToText(n % 1000000);
           else if ( n <= 999999999)
              return NumberToText(n / 1000000) + "Millions " + NumberToText(n % 1000000);
           else if ( n <= 1999999999 )
              return "One Billion " + NumberToText(n % 1000000000);
           else 
              return NumberToText(n / 1000000000) + "Billions " + NumberToText(n % 1000000000);
        }
    }
@"

Add-Type -TypeDefinition $class

[Num2Word]::NumberToText(555)

There's no reason you couldn't write this as pure powershell, but this was already written!

Community
  • 1
  • 1
briantist
  • 45,546
  • 6
  • 82
  • 127