SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    parseFloat - parseInt?? This will be 2 mins for anyone with a little js knowledge...

    Hi there,

    I'm busy with my Js final project at the end of my Js "kinda" beginners course. The website set up for the final project requires a section including a form used to calculate different prices (budgets) for different websites depending on the different options chosen in the form. My last line for this callculation goes like this:

    Code:
    document.getElementById("resultado").value = total + total_check + ' euros';
    The problem is, I know it is not new at all in this forum, that "total" and "total_check" variables, containing numeric values, don't get mathematically added through the line of code I wrote, but written side by side, as two different pieces of text, in the "id:resultado" <input type="text">.

    My doubts:

    1.- Should I have specified through parseInt or parseFloat ("total" variable might result on a decimal value depending on the options chosen in the form), somewhere earlier in the code, that "total" and "total_check" variables would be numeric values used for mathematical operations or is it possible to do it in this last line of code alone?

    2.- If it can be done in this last line, how exactly should this last line look like?


    Thx very much in advance.

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by whitecreek View Post
    1.- Should I have specified through parseInt or parseFloat ("total" variable might result on a decimal value depending on the options chosen in the form), somewhere earlier in the code, that "total" and "total_check" variables would be numeric values used for mathematical operations or is it possible to do it in this last line of code alone?
    It's better to do it as early as you can, to help prevent such issues if you make use of it later on elsewhere too. Since the values will possibly contain a decimal value, it's better to use parseFloat here in this case.

    Quote Originally Posted by whitecreek View Post
    2.- If it can be done in this last line, how exactly should this last line look like?
    Given that this is for a final project, I'll leave this part as an exercise for the reader
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi Paul,

    Thanks for answering.

    I read the info on parseFloat at MDN, which is pretty much the same information given in the book of the course I'm doing. What I don´t get to understand is how to properly use parseFloat. I mean, it seems the string in the function parseFloat [parseFLoat(string);] has to be a number. If there is any text, appart from any number, parseFloat will pay no attention to it, and return only the numeric characters. And if there is only text, parseFloat will return "NaN". So, how do I make it to relate parseFloat to a variable, which is always refered at through text?

    I'm including here the js code for the budget callculation function in order to make myself clearer:

    Code:
    function presupuesto() { 
          var total = document.getElementById("num").value;    	
    	  	  
    	  //cálculo meses 
    	  
    	  if (document.getElementById("meses").value == 1) {
    		  total = total * 0.95;}
    		  	  
    	  if (document.getElementById("meses").value == 2) {
    		  total = total * 0.90;}		  
    		  
    	  if (document.getElementById("meses").value == 3) {
    		  total = total * 0.85;}		 
    		  
    	  if (document.getElementById("meses").value == 4) {
    		  total = total * 0.80;}	 	  
    	  
    	  //checkboxes 
    
             var precio_check = 400; 	  
    	  
    	  if (document.getElementById("quien").checked){
    		  var vquien = precio_check;}
    		  else
    		  {var vquien = "";}
    		  
    	  if (document.getElementById("donde").checked){
    		  var vdonde = precio_check;}
    		  else
    		  {var vdonde = "";}
    		  
    	  if (document.getElementById("fotos").checked){
    		  var vfotos = precio_check;}
    		  else
    		  {var vfotos = "";}
    		  
    	  if (document.getElementById("comerce").checked){
    		  var vcomerce = precio_check;}
    		  else
    		  {var vcomerce = "";}
    		  
    	  if (document.getElementById("gestion").checked){
    		  var vgestion = precio_check;}
    		  else
    		  {var vgestion = "";}
    		  
    	  if (document.getElementById("noticias").checked){
    		  var vnoticias = precio_check;}
    		  else
    		  {var vnoticias = "";}		  
    		 
    	  if (document.getElementById("fbook").checked){
    		  var vfbook = precio_check;}
    		  else
    		  {var vfbook = "";}
    		  
    	  if (document.getElementById("tweeter").checked){
    		  var vtweeter = precio_check;}
    		  else
    		  {var vtweeter = "";}
    		  
    	  var total_check = vquien + vdonde + vfotos + vcomerce + vgestion + vnoticias + vfbook + vtweeter; 	 
    	  
    	  // cálculo del total - tipo de web	     
    	  
          document.getElementById("resultado").value = total + total_check + ' euros';
    }

    Thanks again,


    Whitecreek.

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by whitecreek View Post
    So, how do I make it to relate parseFloat to a variable, which is always refered at through text?
    You would put the name of the variable inside of the parenthesis.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I tried that already and I got "Nan". May be I wasn't doing it right. You mean like for example this?:

    Code:
    document.getElementById("resultado").value = parseFloat(total) + parseFloat(total_check) + ' euros';

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by whitecreek View Post
    I tried that already and I got "Nan". May be I wasn't doing it right. You mean like for example this?:

    Code:
    document.getElementById("resultado").value = parseFloat(total) + parseFloat(total_check) + ' euros';
    Yes, like that.

    So let's take a look at what value is stored in the total variable, and the total_check variable.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The form you can see at: http://www.ficoprieto.com/proyecto_j...esupuesto.html


    total variable would be whatever value chosen through the drop-down menu, initially ""

    total will then have substrated a percentage if at <input type="text" name="meses" id="meses" class="plazo" onKeyUp="presupuesto()" /> the user introduces 1, 2, 3 or 4, as number of months.

    total_check variable would be "" or 400 multiplied by the number checkboxes selected in the form.
    Last edited by whitecreek; May 4, 2012 at 04:11. Reason: I added needed information

  8. #8
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Okay, with the total we have this:

    Code:
    var total = document.getElementById("num").value;
    So the total could be an empty string, or one of the values in the options. The empty string is guaranteed to cause problems here, so you need to ensure that the total variable makes numeric sense here right from the start.

    One way is:

    Code:
    var total = document.getElementById("num").value;
    total = parseFloat(total);
    if (isNaN(total)) {
        total = 0;
    }
    or you could get away with:

    Code:
    var total = parseFloat(document.getElementById("num").value);
    if (!total) {
        total = 0;
    }
    However, the || (OR) operator is also used as a default operator, allowing us to use this sort of code to achieve the same thing:

    Code javascript:
    var total = document.getElementById("num").value;
    total = parseFloat(total) || 0;

    Which attempts to convert the total, and if the total fails for any reason it will default to assigning 0 to the total.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  9. #9
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    By the way, this code can be dramatically improved.

    Code:
    //checkboxes  
      
      
    if (document.getElementById("quien").checked){
        var vquien = precio_check;}
        else
        {var vquien = "";}
    	  
    if (document.getElementById("donde").checked){
        var vdonde = precio_check;}
        else
        {var vdonde = "";}
    		  
    if (document.getElementById("fotos").checked){
        var vfotos = precio_check;}
        else
        {var vfotos = "";}
    		  
    if (document.getElementById("comerce").checked){
        var vcomerce = precio_check;}
        else
        {var vcomerce = "";}
    		  
    if (document.getElementById("gestion").checked){
        var vgestion = precio_check;}
        else
        {var vgestion = "";}
    		  
    if (document.getElementById("noticias").checked){
        var vnoticias = precio_check;}
        else
        {var vnoticias = "";}		  
    		 
    if (document.getElementById("fbook").checked){
        var vfbook = precio_check;}
        else
        {var vfbook = "";}
    		  
    if (document.getElementById("tweeter").checked){
        var vtweeter = precio_check;}
        else
        {var vtweeter = "";}
    
    var total_check = vquien + vdonde + vfotos + vcomerce + vgestion + vnoticias + vfbook + vtweeter;
    Replacing all of that with the following will work better:

    Code javascript:
    //checkboxes  
    var total_check = 0,
        checkboxes = ['quien', 'donde', 'fotos', 'comerce', 'gestion', 'noticias', 'fbook', 'tweeter'],
        i;
    for (i = 0; i < checkboxes.length; i += 1) {
        if (document.getElementById(checkboxes[i]).checked) {
            total_check = precio_check;
        }
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  10. #10
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    All right. I think I got it Paul. Great stuff.

    Just before reading your last answer I thought the empty string could be the problem, since it is neither text nor number (especially not a number which is what is needed in this case!), so I went into the html file >> <form> >> <select> and introduced '0' as the default value for the selected <option>. I did the same, one by one, with all empty string values related to any variable affecting 'var total_check', and it worked .

    In addition I used 'parseInt' for 'total_check', since it will never be a decimal number. It will look better in my project using both functions .

    However I like any of your solutions a lot better. They keep you form making changes in the html which is very often much more comfortable. I like especially the last one. I find it easier to handle. I´m giving serious thoughts to using it

    Thanks a million for your time and help. Appreciated!!

    Best regards,


    Whitecreek.

  11. #11
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by paul_wilkins View Post
    By the way, this code can be dramatically improved.

    Code:
    //checkboxes  
      
      
    if (document.getElementById("quien").checked){
        var vquien = precio_check;}
        else
        {var vquien = "";}
    	  
    if (document.getElementById("donde").checked){
        var vdonde = precio_check;}
        else
        {var vdonde = "";}
    		  
    if (document.getElementById("fotos").checked){
        var vfotos = precio_check;}
        else
        {var vfotos = "";}
    		  
    if (document.getElementById("comerce").checked){
        var vcomerce = precio_check;}
        else
        {var vcomerce = "";}
    		  
    if (document.getElementById("gestion").checked){
        var vgestion = precio_check;}
        else
        {var vgestion = "";}
    		  
    if (document.getElementById("noticias").checked){
        var vnoticias = precio_check;}
        else
        {var vnoticias = "";}		  
    		 
    if (document.getElementById("fbook").checked){
        var vfbook = precio_check;}
        else
        {var vfbook = "";}
    		  
    if (document.getElementById("tweeter").checked){
        var vtweeter = precio_check;}
        else
        {var vtweeter = "";}
    
    var total_check = vquien + vdonde + vfotos + vcomerce + vgestion + vnoticias + vfbook + vtweeter;
    Replacing all of that with the following will work better:

    Code javascript:
    //checkboxes  
    var total_check = 0,
        checkboxes = ['quien', 'donde', 'fotos', 'comerce', 'gestion', 'noticias', 'fbook', 'tweeter'],
        i;
    for (i = 0; i < checkboxes.length; i += 1) {
        if (document.getElementById(checkboxes[i]).checked) {
            total_check = precio_check;
        }
    }
    Ok. I read about the "for (i=0..." in the text book but I didn't feel yet confident or fluent enough to use it, so I went the easy way. Thx very much for the tip. I'll keep it safe


    Best regards!!,


    Whitecreek.

  12. #12
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi again Paul,

    I finally gave a try to the last piece of code you wrote, the one synthesizing the long repetitve chunk I wrote myself in the first place:

    Code:
    //checkboxes  
    var total_check = 0,
        checkboxes = ['quien', 'donde', 'fotos', 'comerce', 'gestion', 'noticias', 'fbook', 'tweeter'],
        i;
    for (i = 0; i < checkboxes.length; i += 1) {
        if (document.getElementById(checkboxes[i]).checked) {
            total_check = precio_check;
        }
    }
    This works and it definetely shortens things up, but it doesn´t really do what I was needing. The idea was adding 400 (euros in this case) to 'total' variable, each time a checkbox is selected. That is, 400 per checkbox selected. And substracting 400 if any of the selected checkboxes is deselected. That is, subtracting 400 per checkbox deselected. The code you wrote equals 'total_check' to 'precio_check' (being this last one a fixed constant value of 400) if there is a checkbox selection, no matter how many checkboxes are selected. If the user ticks on either 1 or 4 checkboxes, for instance, the same value will be added to 'total' variable: 400 only. It doesn't multiply 400 by the number of checkboxes selected.

    I'm not sure if there is an easy way to get that through this shortened code way you wrote...

    Thanks again in advance.

  13. #13
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,687
    Mentioned
    100 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by whitecreek View Post
    That is, 400 per checkbox selected.
    Ahh, well you can use the += operator to add 400 to the total on each occurrence instead:

    Code javascript:
    total_check += precio_check;
    Last edited by paul_wilkins; May 7, 2012 at 02:25.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  14. #14
    SitePoint Enthusiast whitecreek's Avatar
    Join Date
    Aug 2011
    Location
    Madrid, Spain
    Posts
    42
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect. Works just fine.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •