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:

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.

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.

Given that this is for a final project, I’ll leave this part as an exercise for the reader :slight_smile:

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:



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.

You would put the name of the variable inside of the parenthesis.

I tried that already and I got “Nan”. May be I wasn’t doing it right. You mean like for example this?:



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.

The form you can see at: http://www.ficoprieto.com/proyecto_jscript/presupuesto.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.

Okay, with the total we have this:

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:


var total = document.getElementById("num").value;
total = parseFloat(total);
if (isNaN(total)) {
    total = 0;
}

or you could get away with:


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:


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.

By the way, this code can be dramatically improved.


//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:


//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;
    }
}

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 :lol:.

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 :smiley:

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

Best regards,

Whitecreek.

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 :slight_smile:

Best regards!!,

Whitecreek.

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:

//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.

Ahh, well you can use the += operator to add 400 to the total on each occurrence instead:


total_check += precio_check;

Perfect. Works just fine.