Simple Javascript Format and validation questions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Leo Smith
    New Member
    • Mar 2007
    • 45

    Simple Javascript Format and validation questions

    I need to verify that someone has input a number (any numeric value), and then format the output. What is the simplest way to convert a text value in JavaScript to a numeric, int, or float? Next question is then how can I ensure specific format like #,###.00? Also, where is the best location for JavaScript Classes like String, Boolean, Int...?

    Thanks for any help,
    Leo
  • epots9
    Recognized Expert Top Contributor
    • May 2007
    • 1352

    #2
    int:
    [CODE=javasscrip t]var num = parseInt("43")[/CODE]
    float:
    [CODE=javasscrip t]var num = parseFloat("4.5 ")[/CODE]

    depending on what your doing (ie. if your working with money, then u would want float).

    **if the value doesn't/can't be parsed it will returns: NaN (Not a Number), so u'll have to check for that.

    Comment

    • Leo Smith
      New Member
      • Mar 2007
      • 45

      #3
      This is great. How about formatting the output later, like ensuring that there are decimal places for currency, or commas between thousands and hundreds?

      Thanks again,
      Leo

      Comment

      • epots9
        Recognized Expert Top Contributor
        • May 2007
        • 1352

        #4
        this should do the trick:

        [CODE=javascript]
        <!-- Original: Cyanide_7 (leo7278@hotmai l.com) -->
        <!-- Web Site: http://www7.ewebcity.c om/cyanide7 -->

        <!-- This script and many more are available free online at -->
        <!-- The JavaScript Source!! http://javascript.inte rnet.com -->

        <!-- Begin
        function formatCurrency( num) {
        num = num.toString(). replace(/\$|\,/g,'');
        if(isNaN(num))
        num = "0";
        sign = (num == (num = Math.abs(num))) ;
        num = Math.floor(num* 100+0.500000000 01);
        cents = num%100;
        num = Math.floor(num/100).toString() ;
        if(cents<10)
        cents = "0" + cents;
        for (var i = 0; i < Math.floor((num .length-(1+i))/3); i++)
        num = num.substring(0 ,num.length-(4*i+3))+','+
        num.substring(n um.length-(4*i+3));
        return (((sign)?'':'-') + '$' + num + '.' + cents);
        }
        // End -->
        [/CODE]

        Comment

        • Leo Smith
          New Member
          • Mar 2007
          • 45

          #5
          Thanks, this will help alot.

          Comment

          Working...