jQuery - Simple math returning NaN - javascript

I am trying to do some simple math, using below function. The function is called onChange:
var exposure = $('#exposure').find(":selected").val();
var budget = $('.budget').val();
var ppc = $('.ppc').val();
var value = budget/ppc;
var total2 = Math.floor(value*0.95);
if(exposure == 2){
var dref = 0.0005;
}else if(exposure == 3){
var dref = 0.005;
}else if(exposure == 4){
var dref = 0.001;
}
if(exposure > 1){
var add = dref+ppc;
var value2 = budget/add;
var total2 = Math.floor(value2*0.95);
}
$("#sum").text("" + total2 + " Clicks");
My problem is, that if exposure > 1, the total2 value in #sum will return NaN
What am I doing wrong?

Do a parseInt(value,10) for intergers or parseFloat(value) for float.
JavaScript appends the values if the data type is not a number.
Like:
budget = parseInt(budget,10);

You got to use parseInt or parseFloat. I would say parseFloat something like,
var budget = parseFloat($('.budget').val());
var ppc = parseFloat($('.ppc').val());
var value = parseFloat(budget/ppc);
var total2 = parseFloat((value*0.95));

Related

Stop value going into negative in javascript

I have a function where you can click to like, and you kan also click to dislike. How can I make it NOT possible to go to negative number, so that if you click dislike after 0 it stays 0?
function stem(id) {
var antal_stemmer = document.getElementById(id).className;
var nyt_antal_stemmer =+ antal_stemmer + +1;
document.getElementById(id).className = nyt_antal_stemmer;
var indhold = document.getElementsByClassName(id);
var indholdA = indhold[0].innerHTML;
indhold[0].innerHTML = nyt_antal_stemmer + " stemmer";
}
function fjern(id) {
var antal_stemmer = document.getElementById(id).className;
var nyt_antal_stemmer =+ antal_stemmer - +1;
document.getElementById(id).className = nyt_antal_stemmer;
var indhold = document.getElementsByClassName(id);
var indholdA = indhold[0].innerHTML;
indhold[0].innerHTML = nyt_antal_stemmer + " stemmer";
}
You could get the maximum of the value or zero. The result is a number greater or equal zero.
var nyt_antal_stemmer = Math.max(0, antal_stemmer - 1); // - converts the operands to number

How to set auto 2 decimal number using value from id input type="text" javascript?

How to set auto 2 decimal number using value from id input type="text" javascript ?
http://jsfiddle.net/A4wxX/90/
First , fill data eg: 2 into input , it's will update input to 2.00
But not work When i user this
var numb = document.getElementById("int").value;
How can i do ? thank.
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script type="text/javascript">
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = numb.toFixed(2);
document.getElementById("int").value = zzz;
}
</script>
<input type="text" id="int" onchange="fn_do()">
You should use parseFloat, because DOM property value is a string, not number.
var zzz = parseFloat(numb).toFixed(2)
And don't use parseInt, because it'll give you an integer, for example parseInt("1.2") will be 1, then toFixed(2) gives you 1.00, while you actually want 1.20 I assume.
One more thing to care is, make sure input content is valid, for example parseFloat('qwer') will give you NaN. So the final code would look like:
var zzz = (parseFloat(numb) || 0).toFixed(2);
Instead of
var zzz = numb.toFixed(2)
Try
var zzz = parseFloat(numb).toFixed(2) //use parseInt() or parsFloat() as shown here.
Your complete will look like this :-
function fn_do() {
var numb = document.getElementById("int").value;
var zz = parseFloat(numb) || 0; //it will convert numb to float if conversion fails it will return 0.
var zzz = zz.toFixed(2);
document.getElementById("int").value = zzz;
}
Fiddle
var decimalForm = parseFloat(Math.round( intNum * 100) / 100).toFixed(2);
alert(decimalForm );
If I'm understanding this correctly, you want whatever number is put into the object with the id 'int' to be automatically converted to a decimal value with two placeholders. You could do something like this:
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
That would ensure that you always get two decimal places
Exceptions: 1. if tempValue is a multiple of 10, only one decimal will come out
2. if tempValue is a multiple of 100, no decimals will be returned
Solution:
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}
So maybe the whole cde would look like this
function fn_do() {
var numb = document.getElementById("int").value;
//var numb = 123;
var zzz = convertToDecimal(numb);
zzz = zzz + convertDecimal(zzz);
document.getElementById("int").value = zzz;
}
function convertToDecimal(value) {
var tempValue = Nath.Round(parseFloat(value) * 100);
var returnValue = tempValue * .01;
return returnValue;
}
function convertDecimals(convertedValue) {
var tempValue = Nath.Round(parseFloat(value) * 100);
if ((tempValue % 10) == 0) {
if ((tempValue % 100) == 0) { var returnValue = convertedValue + .00; return returnValue; } else {
var returnValue = convertedValue + 0;
return returnValue;
}
}
return '';
}

display in decimal the total of 2 numbers

im trying to display the 2 decimal point of the 2 total number and minus them but it didnt compute the decimal point. anyone would like to figure this out. thanks.
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
var basicpay = document.getElementById('basicpay');
var myResult = myBox1 * myBox2;
basicpay.value = myResult.toFixed(2);
document.getElementById('both').value = sum() - diff();
}
this is the diff part
function diff() {
var absent = document.getElementById('absent').value;
var tardiness = document.getElementById('tardiness').value;
var sss = document.getElementById('sss').value;
var pagibig = document.getElementById('pagibig').value;
var philhealth = document.getElementById('philhealth').value;
var cashadvances = document.getElementById('cashadvances').value;
var withholdingtax = document.getElementById('withholdingtax').value;
var others = document.getElementById('others').value;
var result =
parseInt(absent) +
parseInt(tardiness) +
parseInt(sss) +
parseInt(pagibig) +
parseInt(philhealth) +
parseInt(cashadvances) +
parseInt(withholdingtax) +
parseInt(others) || 0;
if (!isNaN(result)) {
document.getElementById('totaldeductions').value = result.toFixed(2);
return result;
}
}
this is the sum part
function sum() {
var basicpay = document.getElementById('basicpay').value;
var overtime = document.getElementById('overtime').value;
var regularholiday = document.getElementById('regularholiday').value;
var specialholiday = document.getElementById('specialholiday').value;
var allowanceday = document.getElementById('allowanceday').value;
var monthpay = document.getElementById('monthpay').value;
var others1 = document.getElementById('others1').value;
var result =
parseInt(basicpay) +
parseInt(overtime) +
parseInt(regularholiday) +
parseInt(specialholiday) +
parseInt(allowanceday) +
parseInt(monthpay) +
parseInt(others1) || 0;
if (!isNaN(result)) {
document.getElementById('totalgrosspay').value = result.toFixed(2);
return result;
}
}
In your Sum() and Diff() function, you are working only with integers. Integers are whole numbers only, so will not retain anything after a decimal point. To deal with decimals, you will need to use JavaScript's parseFloat() function. To give an example, in your Sum() function you would change the result calculation to look like the following:
var result =
parseFloat(basicpay) +
parseFloat(overtime) +
parseFloat(regularholiday) +
parseFloat(specialholiday) +
parseFloat(allowanceday) +
parseFloat(monthpay) +
parseFloat(others1) || 0;
This will retain the decimal points in the numbers rather than truncating to whole numbers as the parseInt()

How do I randomise multiple groups in a loop?

I am making a little test that people can use to check their knowledge of hiragana.
It randomly selects 4 hiragana from a 2nd array and one correct spelling of the hiragana.
It looks pretty much exactly as it should with one twist. The correct answer is in the same place every time! The second hiragana always shows as correct. This is the code that I have used to randomise. Thanks in advance for your help!
var first = Math.floor((Math.random() * 46));
var second = Math.floor((Math.random() * 46));
var third = Math.floor((Math.random() * 46));
var fourth = Math.floor((Math.random() * 46));
var selector = Math.floor((Math.random() * 4));
var firstHiragana = hiraganaSet[first][0];
var secondHiragana = hiraganaSet[second][0];
var thirdHiragana = hiraganaSet[third][0];
var fourthHiragana = hiraganaSet[fourth][0];
alert(selector)
if (selector = 0){
var romaji = hiraganaSet[first][1];
var romajiData = hiraganaSet[first][0];
}
else if (selector = 1){
var romaji = hiraganaSet[second][1];
var romajiData = hiraganaSet[second][0];
}
else if (selector = 2){
var romaji = hiraganaSet[third][1];
var romajiData = hiraganaSet[third][0];
}
else if (selector = 3){
var romaji = hiraganaSet[fourth][1];
var romajiData = hiraganaSet[fourth][0];
}
http://jsfiddle.net/jB6cp/1/
Most likely because you're assigning values rather than doing a comparison check:
if (selector = 0)
should be
if (selector == 0)
or
if (selector === 0)
depending on how strict you want your check to be.
= assigns the value to the variable.
== does a comparison for value only.
=== does a comparison for value and type.
There's some more information here.

Convert percent into a decimal in html/ javascript

Javascript:
var validate(s) = s.match ^( 100(?:\.0{1,2})? | 0*?\.\d{1,2} | \d{1,2}(?:\.\d {1,2})? )% $ != null;
var str = value.match(/\/\/%//g);
if(converted==NaN){
alert('Input was not a number');
}
else if(converted != null) {
var fracToDecimal = eval (value);
alert(fracToDecimal);
}
else if(converted = str) {
var percToDecimal = value/100;
alert(percToDecimal);
} }
So you have a string like: 50%? How about:
var percent = "50%";
var result = parseFloat(percent) / 100.0;
If you use parseFloat, it will read the string up until the first non-number character (the %)
var x = '20.1%';
var y = parseFloat(x); // 20.1
Then you can check if it's NaN, and convert it.
if(!isNaN(y)){
y /= 100; // .201
}
Note: You need to use isNaN because NaN === NaN is false (JavaScript is weird).
UPDATE: I see you also have fracToDecimal in there. You don't need eval for that. Just do a simple split.
var frac = '1/2';
var nums = frac.split('/');
var dec = nums[0]/nums[1];
Assuming the "%" is on the right hand of the string, just use parseFloat(s)/100
http://jsfiddle.net/TrCYX/1/
I'm very late, but keeping it as itself if it is a decimal goes like this
let val = "100%"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
val = 1 //or val = "1"
String(val).includes("%") ? parseFloat(val)/100 : parseFloat(val) //1
function convertToDecimal(percent) {
let newarr =[]
for(i=0; i<percent.length; i++) {
const parsed = parseFloat(percent[i]);
if (!Number.isNaN(parsed[i])) {
let newval = parseFloat(percent[i]) / 100;
//return newval;
newarr.push(newval)
} else {
return 0;
}
} return newarr;
}
console.log(convertToDecimal(["33%", "98.1%", "56.44%", "100%"]))

Categories