Number (0-100) to String

I could not find the thread, but remember about a week ago that someone had asked about turning a given number in the range 0-100 into its string equivalent.
Here's a little class that does it. Hope it helps...
package
    public class NumberToText    {
        private var numStrings:Array;
        private var tenStrings:Array;   
        public function NumberToText()
            numStrings = new Array();
            tenStrings = new Array();
            numStrings.push("Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");           
            tenStrings.push("Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "One Hundred");
        public function numToString(num:int):String
            if (num < 20) {               
                return numStrings[num];
            var tensPlace:int = 0;
            var cur:int = num;
            while (cur >= 10) {
                cur -= 10;
                tensPlace++;
            var rem:int = num - (10 * tensPlace);
            var tens:String = tenStrings[tensPlace - 2];
            if (rem == 0) {
                 return tens;   
            }else {
                 return tens + " " + numStrings[rem];   
            return "null";

Nice.
But I think the code below is more compact and efficient - it uses math only and no loops:
package
     public class NumberToText {
          private var numStrings:Array = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
          private var tenStrings:Array = ["Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "One Hundred"];  
          public function NumberToText()
          public function numToString(num:int):String
               if (num < 20) {              
                    return numStrings[num];
               else if (num <= 100){
                    return  tenStrings[int(num / 10) - 2] + " " + (num % 10 > 0 ? numStrings[num % 10] : "");
               else {
                    return "null";
Also, as a utility, it can use Math.method notation - static function:
package
     public class NumberToText {
          public function NumberToText()
          public static function numToString(num:int):String
               var numStrings:Array = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
               var tenStrings:Array = ["Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "One Hundred"];
               if (num < 20) {              
                    return numStrings[num];
               else if (num <= 100){
                    return  tenStrings[int(num / 10) - 2] + " " + (num % 10 > 0 ? numStrings[num % 10] : "");
               else {
                    return "null";
So, usage will be:
var numString:String = NumberToText.numToString(89);
Or, perhaps, it can be written as package level function, similar to navigateToURL with usage:
var  numString:String = numToString(89);
package 
     public function numToString(num:int):String
          var numStrings:Array = ["Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"];
          var tenStrings:Array = ["Twenty", "Thirty", "Fourty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety", "One Hundred"];
          if (num < 20) {              
               return numStrings[num];
          else if (num <= 100){
               return  tenStrings[int(num / 10) - 2] + " " + (num % 10 > 0 ? numStrings[num % 10] : "");
          else {
               return "null";

Similar Messages

  • Needed program unit to translate number as currency to string

    HI All,
    Can you please tell me if there is existing program unit that i can use to translate number as currency to string
    Ex:
    i have numbeer like 110.5 and currency code EGP
    i need the program unit to return
    Only One Hundred Ten Egyptian Pound (s) and Fifty Piaster (s)
    for ococourse if the EGP is USD it'll return dollar instead of egyptian pound
    Thanks you

    Yeah i already did so and i got the function and used it my problem just in the currency translation for decimals
    that means when i need to translate 100.5 EGP
    one hundred Egyptian Pounds and fifty piasters
    i can now translate to one hundred Egyptian Pounds and fifty but what about the piasters
    i think i had to create a table that contains a currency code and the corresponding currency translation piasters , cents , ...etc
    so i think i'll have to search on google about the currency transaltion for the decimal point currency i hoped there is a tabke in the e-business suite contains it as it exists for the currency code

  • Server 2012 errors for timeout -- LDAP error number: 55 -- LDAP error string: Timeout Failed to get server error string from LDAP connection

    Hello, currently getting below error msg's utilizing software thru which LDAP is queried for discovering AD objects/path and resource enumeration and tracking.
    Have ensured firewalls and port (389 ) relational to LDAP are not closed, thus causing hanging.
    I see there was a write up on Svr 2003 ( https://support.microsoft.com/en-us/kb/315071 ) not sure if this is applicable, of if the "Ntdsutil.exe" arcitecture has changed much from Svr 03. Please advise. 
    -----------error msg  ----------------
    -- LDAP error number: 55
    -- LDAP error string: Timeout Failed to get server error string from LDAP connection

    The link you shared is still applicable. You can adjust your LDAP policy depending on your software requirements.
    I would also recommend that you in touch with your software vendor to get more details about the software requirements.
    This posting is provided AS IS with no warranties or guarantees , and confers no rights.
    Ahmed MALEK
    My Website Link
    My Linkedin Profile
    My MVP Profile

  • What api would I use to get the number of chars in string?

    What api would I use to get the number of chars in string?

    Assuming that you really mean that you want the number of charaters in a String (not string), that would be documented in java.lang.String
    The method is length()

  • Number representation of a string..

    Hi all,
    I want to get a number representation of a string. The string could be anything.
    I do not need to be able to convert it back.
    How can I do this?
    No length or adding up the char codes is not good as ABD would be the same as BAD etc.
    Well - A hash would do.
    I've just found get_hash_value so that may be sufficient.
    Edited by: user10071099 on Jun 17, 2009 10:02 AM

    You could use rawtohex function for that ( or , if there should be no relation between string content and the number - you can use any of popular hash functions , such as sha1 or md5)
    Best regards
    Maxim

  • Find number of lines a string will wrap to?

    I'd like to find the number of lines a string will wrap to, given a font and a width.
    Is this possible?
    Thanks

    You could get the height of resulting string using sizeWithFont:constrainedToSize, and then divide it by the height of one line (computed using the saem function with jsut one letter).

  • Number of character in string

    Hi,
    How to Find number characters in a string.(not length), The string contains characters of english ,japanese & numericals also.
    Iam splitting the string by 2 length through FM 'split_text' and the and how to find the splitted part has japanese character or english character.
    \[removed by moderator\]
    Regards,
    Narasimhulu P
    Edited by: Jan Stallkamp on Jul 11, 2008 10:36 AM

    Hi Narasimhulu,
    There is System field called sy-abcde which conains all the English letters.
    If your string contains only english and Japanees chars,
    You can check with SY-ABCDE like below.
    DATA:
       w_urstring TYPE STRING.
      w_urstring = 'こんにちは。 Konnichiwa'.
      if  w_urstring ca sy-abcde.
        split  w_urstring into  w_urstring1  w_urstring2.
        if sy-subrc eq 0.
         write:
           /  w_urstring1, w_urstring2.
         endif.
    endif.
    hope this solves ur proble.
    Regards, 
    Rama chary.

  • [CS3][JS] How to turn negative number in array into string

    Hello,
    I have a script that compares the array of the geometric bounds of all text frames to the margins for a document (all pages having the same margins). Any frames that do not match the margins are flagged.
    In order to compare the array of text frame geometric bounds to two arrays of margins (because they are facing pages), I have to convert the numbers to strings.
    My problem is that in the following snippet of code that creates the two margin arrays, the negative of the variables become numbers again. This would not be too difficult to solve except that all the numbers have to be 4 decimal points before converted to strings.
    Thanks,
    Tom
    var myDoc = app.activeDocument;
    var marginY1 = myDoc.pages.item(0).marginPreferences.top.toFixed(4);
    var marginX1 = myDoc.pages.item(0).marginPreferences.left.toFixed(4);
    var marginY2 = (myDoc.documentPreferences.pageHeight - myDoc.pages.item(0).marginPreferences.bottom).toFixed(4);
    var marginX2 = (myDoc.documentPreferences.pageWidth - myDoc.pages.item(0).marginPreferences.right).toFixed(4);
    var marginsRHand = [marginY1, marginX1, marginY2, marginX2];
    var marginsLHand = [marginY1, -marginX2, marginY2, -marginX1];

    Well, I think I have solved it. But I don't know why this solves it.
    I would think that in the above script all the variables would be numbers and not strings. But the data browser says they are strings.
    The solution is:
    var marginsLHand = [marginY1, Number(-marginX2).toFixed(4), marginY2, Number(-marginX1).toFixed(4)]
    If someone can explain why now all variables in the arrays are strings and not numbers, I'll be happy.
    Tom

  • Trying to determine the last occurence of a number within a word string.

    Hi All,
    I am trying to find the last occurence of a number within a string. I have had a quick look at the Java Tutorial and know about lastIndexOf and substring. The thing is I have to test for the existance of the numbers 0-9 within a product code that typically looks like this:
    s1_14G12B
    s1_17G1BA
    s2_24GD
    The only part of the above strings that I am interested in is the letter(s) that follow the very last number, so in the case of those codes presented above, I would like to extract the following:
    B
    BA
    D
    I have written some code that performs a similar operation:
    public class FindPriceCode
      private String priceCode;
      private String[] numberValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
      public FindPriceCode()
        priceCode = "s2_71G4BA";
        for(int i=0; i<numberValues.length; i++)
          int location = priceCode.lastIndexOf(numberValues);
    System.out.println("Character " + numberValues[i] + " found at position: " + location);
    public static void main(String[] args)
    FindPriceCode myPriceCode = new FindPriceCode();
    ...finding the location of numberValues string within the given example code. I am now at a loss as to how I can determine the location of the last number occurence (moving right to left) and then build a substring from that number. Any help will be greatly appreicated.
    Thanks
    David

    Hello,
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CutNumberTest extends JFrame implements ActionListener {
         private JTextField input= new JTextField(10);
         private JTextArea result=new JTextArea(10,10);
         char[]numbers=new char[]{'0','1','2','3','4','5','6','7','8','9'};
         public CutNumberTest() {
              super("CutNumberTest");
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              JButton cutButton = new JButton("cut number");
              cutButton.addActionListener(this);
              JPanel topPanel=new JPanel();
              JLabel label=new JLabel("Please enter price-code:");
              topPanel.add(label);
              topPanel.add(input);
              topPanel.add(cutButton);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              getContentPane().add(new JScrollPane(result));
              pack();
              setLocationRelativeTo(null);
         public void actionPerformed(ActionEvent e) {
              char[] code=input.getText().toCharArray();          
              int counter=code.length;
              boolean lastNumFound=false;
              while(!lastNumFound && --counter >= 0)
                   lastNumFound=isNumber(code[counter]);
              result.append(lastNumFound ? "result: "+input.getText().substring(counter+1)+"\n" : "No number found!\n");
         private boolean isNumber(char chr){
              boolean isNumber=false;
              int counter=-1;
              while(++counter < numbers.length && !isNumber)
                   isNumber=numbers[counter]==chr;
              return isNumber;
         public static void main(String[] args) {
              new CutNumberTest().setVisible(true);
    }//copy/paste:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class CutNumberTest extends JFrame implements ActionListener {
         private JTextField input= new JTextField(10);
         private JTextArea result=new JTextArea(10,10);
         char[]numbers=new char[]{'0','1','2','3','4','5','6','7','8','9'};
         public CutNumberTest() {
              super("CutNumberTest");
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              JButton cutButton = new JButton("cut number");
              cutButton.addActionListener(this);
              JPanel topPanel=new JPanel();
              JLabel label=new JLabel("Please enter price-code:");
              topPanel.add(label);
              topPanel.add(input);
              topPanel.add(cutButton);
              getContentPane().add(topPanel, BorderLayout.NORTH);
              getContentPane().add(new JScrollPane(result));
              pack();
              setLocationRelativeTo(null);
         public void actionPerformed(ActionEvent e) {
              char[] code=input.getText().toCharArray();          
              int counter=code.length;
              boolean lastNumFound=false;
              while(!lastNumFound && --counter >= 0)
                   lastNumFound=isNumber(code[counter]);
              result.append(lastNumFound ? "result: "+input.getText().substring(counter+1)+"\n" : "No number found!\n");
         private boolean isNumber(char chr){
              boolean isNumber=false;
              int counter=-1;
              while(++counter < numbers.length && !isNumber)
                   isNumber=numbers[counter]==chr;
              return isNumber;
         public static void main(String[] args) {
              new CutNumberTest().setVisible(true);
    Regards,
    Tim

  • How to search for a number located anywhere in string

    I am trying to search a string for a number (integer or float) without knowing its index in the string and to extract it - whether in numeric or string format.  e.g. "the number 52.63 appears in this string"; I want to extract/identify "52.63"
    The functions I come across seem to expect the index to be known or the number to be at index 0.  How can I achieve this?
    Best regards.
    Kenoss
    Solved!
    Go to Solution.

    If you are about to dive into the 'wonderfull world of Regular Expression' don't miss this (regular-expressions.info) site.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • Increment the number with date/time string. when ever the next date come's it should reset again with initial number

     i want to store the number of records in a file. Every time when ever i run the program the record will be incremented well i using forloop with count value 1 as a constant .in the for loop i am using autoincrement with the  feedback node . to view the number i have attached the indicatator .the number will be increment every time . i am using number to time time stamp  that is connected to get date/time string. from that we can view the date string and time string . so , my issue is when ever i close the code again it is coming with intial value . i should get from that number only where ever i close the code . after the date completed again it should come from intial value . i am attaching the code so that u guys can solve my problem.
    Attachments:
    record.doc ‏34 KB

    here you can see.......the file path in case structure in that i have included my requirement of increment the number 
    -> if the case is true then it goes in ok file path and the no of records string will pass in the file by seeing these code u will get the clarity
    my requirement is the number of records should increase ........ whnever the program runs...that i made it. by the next day again it should begain with the intial value.........that is my requirement. i hope u understand .
    suggest me how can i use the  intial  value .......
    Attachments:
    code.vi ‏35 KB

  • Number format changed to string in excel

    I want to store a table in excel file and in the table
    there is a number field that when I store it in the
    excel file ,I want it change to String format,
    because when it store it in the number format,
    it is a wrong number.
    thanks in advance

    "883923"
    Pretend you are explaining this to someone who has no idea what you are talking about (because we don't).
    Statements like "but therewas a problem" are next to meaningless because you didn't explain what the problem is.
    You don't give any useful information such as:
    * Version of JDeveloper/ADF
    * What technologies are you using (I guess ADF Faces, but I don't know)?
    * How did you try exporting to Excel?
    * What was the exact problem you had?
    I've already spent more time thinking about how to ask you questions to get to the real problem than you have formulating your question.
    John

  • How to extract a number between () in a string

    Dear All,
    I have strings like the following:
    DAC (450) DTO Ops (200) DMC (150) RMC (250)
    BCA (50) RMC (200) DMC (60) DAC (870)  DTO Ops (1530)
    DTO Arp (24.48) DTO Ops (173.8124) DM (5.7848)
    I would like to extract selectively all DAC numbers assuming that the position of DAC number in the string is random but the number is always coming between () after "DAC" and 1 space.
    Thanks
    Regards
    Ehfa Dil

    Thanks Zack and Sanjay for your help! Really appreciated!
    Hi Sanjay,
    Your suggestion is working but I get errors when I have some database records with no "DAC " String
    like this one: DTO Arp (24.48) DTO Ops (173.8124) DM (5.7848)
    I have a 1 TB database with many similar records unfortunately... 
    I am not good in programing but I am wondering if there is a script to avoid such errors. I have a workaround with Select expert in Crystal Reports but it is not convenient If I want to publish reports. Would be good if I can put (if expression or anything that could take such case out of errors) any ideas that could help?
    Thanks Again
    Regards
    Ehfa Dil

  • Retreiving number and characters from string

    Hello fellow developers,
    Lets say i have the following string ER686 and want to split the string into a number and characterpart resulting in a String "ER" and an int "686". What is the best approach to accomplish this?
    Thank you for any help offered.

    The format is that there's a sequence of strings 2 or
    3 and a squence of numbers 3 or 4You might use a Pattern matcher, using a regular expression like the following :"(\\D{2,3})(\\d{3,4})"This expressions represents "two or three non-digit characters followed by 3 or 4 digits". The parenthesis are here to allow getting the two elements (groups) separately.
    Use the find() method of the matcher, then retrieve the two groups with group(1) and group(2).
    Eventually, parse the latter if required.

  • Replace Number of Occurences in String

    Hi All,
    I just wanted to know what is the best way to replace a string within another string for certain number of times.
    I dont want to replace only the first one.
    I dont want to replace all of them either.
    i'm looking for something like this:
    replace(input_str, old_str, new_str, nb_occurences)
    e.g: replace("1xxxx0xxxx4","xx",HH,3) should print 1HHHH0HHxx4
    Thanks a lot in advance.

    Better to use regex. I'd throw this away.Actually, he is using regex, but that just makes it worse. I'd throw it away, too.
    What's wrong with java.lang.String's replaceAll method?He's doing a specific number of replacements, i.e., more than one, but not all.
    There's so much wrong with that code, all I can say is to re-read the last line of my previous reply and DON'T USE RECURSION! Also, please abide by the Java naming conventions: method and variable names should start with lowercase letters and should always use camelCase, not under_scores. In the meantime, here's a somewhat radical solution: public class Test
      public static void main(String... args)
        String str = "One and two and three and four and five";
        System.out.println(replaceSome(str, "and", "OR", 0));
        System.out.println(replaceSome(str, "and", "OR", 2));
        System.out.println(replaceSome(str, "and", "OR", 3));
        System.out.println(replaceSome(str, "and", "OR", -1));
      static String replaceSome(String orig, String oldStr, String newStr, int reps)
        String[] parts = orig.split("\\Q" + oldStr + "\\E", reps + 1);
        int n = parts.length - 1;
        if (n > 0)
          StringBuilder sb = new StringBuilder();
          for (int i = 0; i < n; i++)
            sb.append(parts).append(newStr);
    sb.append(parts[n]);
    return sb.toString();
    else
    return parts[0];

Maybe you are looking for