JavaScript Calculation Problem - NaN message - javascript

I'm calculating a total number. I get the sum values from div's. But in total, instead of numbers I get (NaN - Not a Number)
JavaScript Function:
<script type="text/javascript">
function calculateTotal(){
var total = document.getElementById('valor1').innerHTML*1 + document.getElementById('valor2').innerHTML*1 + document.getElementById('valor3').innerHTML*1 + document.getElementById('valor4').innerHTML*1 + document.getElementById('valor5').innerHTML*1 + document.getElementById('valor6').innerHTML*1;
document.getElementById('total').innerHTML = total;
}
</script>
EDIT:
I found the error, I had a closing tag inside the DIV's like this:
<center><div id="valor1"></center></div>
Changed to:
<center><div id="valor1"></div></center>

You cannot use document.getElementById('valor1').innerHTML directly. You have to convert this to number. Please try this.
var value = document.getElementById('valor1').innerHTML;
var number = parseFloat(value)||0;
Do this for each div innerHTML which have number.
var number = parseFloat(value)||0;
The above line will help you to assign 0 to value if div is empty or div html cannot be converted to a number.

Use parseFloat(document.getElementById('x').innerHTML) to convert them to numbers before performing operations:
var total = parseFloat(document.getElementById('x1').innerHTML) + parseFloat(document.getElementById('x2').innerHTML);
You also may want to check them if they're numeric, here's a simple test using isNaN:
alert((isNaN("23"))?'not number':'number');

HTML:
<div id="valor1">2</div>
<div id="valor2">2</div>
<div id="valor3">ccccc</div>
<div id="valor4">2</div>
<div id="valor5">2</div>
<div id="valor6">2</div>
<hr/>
<div id="total">0</div>
JavaScript:
function $(id) { return document.getElementById(id); }
function get(elem) { return parseFloat($(elem).innerHTML) || 0; }
(function() {
var total =
get('valor1') * 1 + get('valor2') * 1 + get('valor3') * 1 +
get('valor4') * 1 + get('valor5') * 1 + get('valor6') * 1;
$('total').innerHTML = total;
}());
A little optimization of the work and demo.
But why stop here? :) we can make it even better ( I think ):
function get(elem) {
return (parseFloat($(elem).innerHTML) || (function() {
$(elem).innerHTML += " <i>Not a number assumed 0</i>";
return 0;
}()));
}
And the updated demo.
Edit: no errors on Chrome & Mozilla (Linux).

try using parseInt() as in
var total = parseInt(document.getElementById('valor1').innerHTML)*1 + parseInt(document.getElementById('valor2').innerHTML)*1 + ... ;
etc etc
this will ensure that what you're getting out of the fields is in fact, a number

Did you try to put these parts into brackets?
(document.getElementById('valor1').innerHTML * 1) + ...
See: http://rx4ajax-jscore.com/ecmacore/operator/predence.html
Even better - use the parseInt(var string) function;
parseInt(document.getElementById('valor1').innerHTML) + ...

Related

Pure Javascript - Turn number into a %

My program spits out a number between 0 and 1, and I cant change that. I need to turn it into a % to use as a variable for a CSS selector.
<div id="Value">0.50</div>
<script>
var element = document.getElementById("Value");
var percent = element * 100;
</script>
But how am I meant to put a % symbol on the end so I can do this:
document.getElementById("circle").style.marginLeft = percent;
Any help would be appreciated, thank you.
String concatenation:
document.getElementById("circle").style.marginLeft = percent + "%";
Since "%" is a string, percent will get converted to string and then the result will be the percent value followed by "%".
As Federico pointed out, you should be using either .value (if the id="Value" element is a field element [an input, textarea, or select]) or .textContent or .innerHTML (if it's not). In your case, it's a div, so textContent would make sense:
var value = document.getElementById("Value").textContent;
var percent = value * 100; // Implicitly converts `value` to number
document.getElementById("circle").style.marginLeft = percent + "%"; // Implicitly converts `percent` to string
try
circle.style.marginLeft = Value.innerText*100 + '%'
<div id="Value">0.50</div>
<div id="circle">◉<div>
document.getElementById("circle").style.marginLeft = percent + '%';
When used on strings, the + operator is called the concatenation operator.
Reference: Javascript Operators
This should solve it.
document.getElementById("circle").style.marginLeft = percent+"%";
In Javascript you can concat natively an int and a string using the '+' operator which means that -
var a = 5
var b = a + '%'
result is b = '5%'
Use innerHTML to get the text from the element
var element = document.getElementById("Value").innerHTML;
var percent = parseFloat(element)*100;
percent+='%';
console.log(percent)
<div id="Value">0.50</div>

Trying to generate a random integer within a specific range then have it displayed inline

So, here's what I have (I am running JQuery):
http://jsfiddle.net/KDmwn/111/
The computer chose <span id="x"></span>.
$(document).ready(function () {
var x = function getRandomInt(1, 4) {
return Math.floor(Math.random() * (4 - 1 + 1)) + 1
};
$('#x').html(x);
}
I feel like the issue has to do with this $('#x').html(x);
Any help is much appreciated. Thanks!
The issue is because your x function has two integers set as the arguments, which is syntactically incorrect.
To achieve what you need you should remove the integers in the argument list, fix the mis-matched bracket at the end of the DOMReady handler and you can also remove the - 1 + 1 from the Math.random value.
Try this:
var x = function getRandomInt() {
return Math.floor(Math.random() * 4) + 1;
}
$('#x').html(x);
Updated fiddle
Use below code
$('#x').html(Math.floor(Math.random() * 4 ) + 1);
Fiddle

Javascript Math.floor issue between specific range of numbers

I'm facing an issue with Math.floor function of javascript for the below scenario:
1) from the value betwwen 8192 and 10484,
if I type 8192.8 -> The Math.floor converts it into 8192.79
if I type 8192.88 -> The Math.floor converts it into 8192.87
if I type 8192.3 -> The Math.floor converts it into 8192.29
Strange part is that except from the range given above the function works fine.
HTML:
<div data-bind="text: popIncrease"></div>
<input type="text" data-bind="value: userInput, valueUpdate: 'afterkeydown'" />
Javascript:
var ViewModel = function () {
var _self = this;
_self.userInput = ko.observable();
_self.popIncrease = ko.computed(function () {
return parseFloat((Math.floor(_self.userInput() * 100) / 100)).toFixed(2);
});
};
ko.applyBindings(new ViewModel());
jsfiddle:https://jsfiddle.net/91z5bdy4/1/
When I changed 100 with 1000 it solved the error but I do not understand why this happened on the first place?
You can just switch to this:
return parseFloat(_self.userInput()).toFixed(2);
Working version of your jsFiddle: https://jsfiddle.net/jfriend00/5rLL04Lk/
Or, if you want to work around some of the idiosyncrasies of .toFixed(), you can use this:
return (Math.round(_self.userInput() * 100) / 100).toFixed(2);
Working jsFiddle: https://jsfiddle.net/jfriend00/xx2aj2L0/
This solution passes all three of your test cases.
It's not Math.floor() that causes the problem, it is the inexactness of the floating point arithmetic. When you multiply 8192.8 by 100, you get 819279.9999999999.
Perhaps you should just manipulate it as a string:
function floorString(str) {
var pos = str.indexOf('.');
return (pos >= 0) ? ((str + '00').slice(0, pos + 3)) : (str + '.00');
}
jsfiddle
The order of your floor/parse seems out of order to me.
Try:
return Math.floor(parseFloat(_self.userInput())).toFixed(2);
Though be aware that 1.999999999999999999999999999999 gives 2.00 using the above; this is because floating point numbers aren't able to represent all values precisely.
another one without using a Math function (2 lines without formatting)
function floorString(str) {
var matches = str.match(/([\d]+(\.[\d]{0,2}))/);
return matches === null || matches[2].length === 1 ?
(str + ".00").replace("..", ".") :
matches[2].length < 3 ?
matches[0] + "00".substr(3 - matches[2].length) :
matches[0];
}

Javascript comparison not working properly

I'm working with the billing part of my system and I put an event in my TextBox using javascript and I have two textboxes. First is the cashonhand and change textboxes. But what I'm wondering is why the comparison between two textboxes is not giving me the right answer. Here is my code:
$(document).ready(function () {
$(document).on('click', '.btn-pay-bill', function () {
var cash = parseFloat(Number($('.cashonhand').val())).toFixed(2);
var amtdue = parseFloat(Number($('.amtdue').text())).toFixed(2);
if (cash <= amtdue) {
alert(cash + ' ' + amtdue + ' ' +"Insufficient Cash!!!");
return false;
}
if (cash >= amtdue) {
return true;
}
return false;
});
SO what am I missing here? Here is the output when I compare 100,000 to 78,200.00:
You're comparing alphabetically instead of numerically.
Note that .toFixed() returns a string:
Returns
A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place.
You'll want to do this comparison before you call .toFixed()
var cash = parseFloat(Number($('.cashonhand').val()));
var amtdue = parseFloat(Number($('.amtdue').text()));
if (cash <= amtdue) {
alert(cash.toFixed(2) + ' ' + amtdue.toFixed(2) + ' ' +"Insufficient Cash!!!");
return false;
}
You can just call .toFixed() wherever you display the number in the UI, or create a separate string version of the value, such as sCash and sAmtDue or something.

Sum two values in javascript

this I think will be stupid question, but here it goes.
I need to dynamically add a div and give it ID + 1 depending on last added div's ID of previously added element.
the div is
<div id="file-uploader-0" class="file-uploader"></div>
So I roughly came out with that code:
$('#addOneMoreFileOrGroup').on('click', function(){
var latestFileUploaderId = $('.well-large .file-uploader').last().attr('id').split('-')[2] + 1;
$('.well-large .control-group:last').after('<div class="control-group deal-type-online"> \
<label class="control-label">File / File Group Title:</label> \
<div class="controls"> \
<input class="span4 file-title" type="text"> \
<span class="question label label-warning" data-title="File / Group Name:" data-content="Name for your file or group of related files (for example your brand logotype in different file formats)." data-original-title="">?</span> \
<div id="file-uploader-' + latestFileUploaderId + '" class="file-uploader"></div> \
</div> \
</div>');
});
But the problem is that in the end of all that I receive "file-uploader-01", "file-uploader-011", "file-uploader-0111".
I tried to use "latestFileUploaderId++" which giving me right result once as "1" and after going as "11", "111", "1111".
Thank you for the tips and help!
Change this:
var latestFileUploaderId = $('.well-large .file-uploader').last().attr('id').split('-')[2] + 1;
to this:
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2],10) + 1;
You're adding a string to a number, which causes the + operator to do string concatenation.
Convert the string to a number first.
var latestFileUploaderId = parseFloat($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;
Convert the string from the id to integer to increment it correctly:
var lastID = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]);
var latestFileUploaderId = lastID + 1;
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2],10) + 1;
You are cocatenating a string and a number... parseInt will convert the string to its numerical value and then the addition will work.
You should use parseInt:
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;
You can use parseInt() to convert the id to a number.
var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;
$('.well-large .file-uploader').last().attr('id').split('-')[2]
is a string. You need to parse it to a int(float).
try using parseInt, parseFloat
You need to cast the value to a Number. Like this:
var latestFileUploaderId = Number($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;
As others have said, you need to change the variable to a Number first, but I wouldn't use parseInt() or similar. Instead, multiplying by 1 is much faster, so something like this is what I'd recommend:
var last = $('.well-large .file-uploader').last().attr('id').split('-')[2];
var latestFileUploaderId = (last * 1) + 1;
JavaScript uses the + operator to concatenate strings which happens in your case. Only numerical types are summarized arithmetically.
In order to increment the ID you have to cast it to an integer before.
console.log ('1' + 1 );
String '11'
console.log( parseInt('1') + 1 )
Int 2

Categories

Resources