By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,377 Members | 1,690 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,377 IT Pros & Developers. It's quick & easy.

Simple Javascript Format and validation questions

P: 45
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
Jun 13 '07 #1
Share this Question
Share on Google+
4 Replies


epots9
Expert 100+
P: 1,351
int:
Expand|Select|Wrap|Line Numbers
  1. var num = parseInt("43")
float:
Expand|Select|Wrap|Line Numbers
  1. var num = parseFloat("4.5")
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.
Jun 13 '07 #2

P: 45
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
Jun 13 '07 #3

epots9
Expert 100+
P: 1,351
this should do the trick:

Expand|Select|Wrap|Line Numbers
  1. <!-- Original:  Cyanide_7 (leo7278@hotmail.com) -->
  2. <!-- Web Site:  http://www7.ewebcity.com/cyanide7 -->
  3.  
  4. <!-- This script and many more are available free online at -->
  5. <!-- The JavaScript Source!! http://javascript.internet.com -->
  6.  
  7. <!-- Begin
  8. function formatCurrency(num) {
  9. num = num.toString().replace(/\$|\,/g,'');
  10. if(isNaN(num))
  11. num = "0";
  12. sign = (num == (num = Math.abs(num)));
  13. num = Math.floor(num*100+0.50000000001);
  14. cents = num%100;
  15. num = Math.floor(num/100).toString();
  16. if(cents<10)
  17. cents = "0" + cents;
  18. for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
  19. num = num.substring(0,num.length-(4*i+3))+','+
  20. num.substring(num.length-(4*i+3));
  21. return (((sign)?'':'-') + '$' + num + '.' + cents);
  22. }
  23. //  End -->
  24.  
Jun 13 '07 #4

P: 45
Thanks, this will help alot.
Jun 13 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.