Error in decimal division result in javascript - javascript

I'm going to do a little javascript operation on my HTML page.
I have no problem dividing 2 numbers by each other.
But if I get the same number from the html input section, the result is wrong.
Sample
total = 99.90/1.08
The result of this operation 92.50 yes I want to find this result.
But when I get the number 99.90 from input in html
total = input/1.08
The result is 91.66
How can I fix this?
function kdv_fiyat_1_1_i() {
var kdv_fiyat_1_1;
kdv = parseInt(document.getElementById('kdv').value);
fiyat = parseInt(document.getElementById('fiyat_1_1').value);
toplam = fiyat/1.08;
kdv_fiyat_1_1 = toplam
document.getElementById('fiyat_1_1').value = kdv_fiyat_1_1;
}

function kdv_fiyat_1_1_i(){
var kdv_fiyat_1_1;
kdv= parseInt(document.getElementById('kdv').value);
fiyat= parseInt(document.getElementById('fiyat_1_1').value);
toplam = fiyat/1.08;
kdv_fiyat_1_1= toplam
document.getElementById('fiyat_1_1').value = kdv_fiyat_1_1;
}
Just changed few things and I think its should work just fine.
What I did is I removed the parseInt and instead added a + operator, what this does is it converts the string to a Number, and yeah it pretty much does the job, if your logic was correct then you should get your desired output

Related

Javascript ParseFloat to autofill without decimals

I have some inputs in a HTML form using javascript to autofill the inputs on changes
The problem is that the follow code show decimals longer decimals like this 42880.34623465464356435634 The code is:
thetotal.value = parseFloat(total.value) * (1.00/1.19);
This code get the price less taxes from the total and it works, but it show me the decimals...
What I need is the price to be in the example:
42880
Without dots or commas . or , like 42.880 or 42,880 and absolutly not 42880.34623465464356435634
I only want to show 42880
Tried with .round like this:
thetotal.value = parseFloat(total.value) * (1.00/1.19).round(2);
.round(2) but for some reason the addEventListener stop working for this input when using .round(2)
user parseInt function for it. Like below :
thetotal.value = parseInt(parseFloat(total.value) * (1.00/1.19));
You will get only Integer as output.
Another way is Math.round. Like it below :
thetotal.value = Math.round(parseFloat(total.value) * (1.00/1.19));
why don't you use Math.round()?
var total = {};
total.value = 51027.6120192;
var thetotal = {};
thetotal.value = Math.round(parseFloat(total.value) * (1.00/1.19));
document.write(thetotal.value);
Output
42880

Take tag value and do an arithmetic operation with jquery

This can be sound ridiculous, but i really want to know if this is possible, and how to make it.
This is my first time in StackOverflow about asking, because i learn here how to code with style, sure with the questions of people like me. Thanks for make me feel like if Stackoverflow is were my house.
Let's ask.
I'm making a php script, more faster than Donald Trump begun to hate the Oreo's cookies.
The script prints this as code HTML
<strong>$</strong><h1>1800</h1>USD
<strong>$</strong><h1>800</h1>USD
So, this is when the mad situation comes...
Whit Jquery i want to take the both h1 elements and i want to make aritmetic operations whit them. I can do this with php and mysql, i know. But about time, i prefer to do this with jQuery.
¿Is there anybody to can help me?
Crazy and very very simple example:
H1 + H1 OR H1 - H1 = NUMBER RESULT OF THE OPERATION.
If you want to get the summation, you can use this code :
var total = 0;
$("h1").each(function(index, item) {
total += Number($(item).text());
});
alert(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<strong>$</strong><h1>1800</h1>USD
<strong>$</strong><h1>800</h1>USD
You can use jquery .each(function(){}) to iterate and find out text in each of h1 tag.For demo I put them inside an array and can apply any mathematical operation
var a=[];
$('h1').each(function(){
var tempText = $(this).text().trim(); // Remove white space
console.log(tempText)
a.push(tempText)
})
Edit
Use parseInt to convert it to integer
`var tempText = parseInt($(this).text().trim());` // Converts to integer
So a will be now an array of integers
Example
Hello you can do it like this
var sum = 0;
$('h1').each(function(k,v){
sum += parseInt($(v).text())
})
console.log(sum)
Crazy and very simple:
$("strong")
.next("h1")
.get()
.map(function(el){
return $(el).text();
})
.reduce(function(a,b){
return parseInt(a)+parseInt(b);
})
[ https://jsfiddle.net/hLwxrpoq/ ]
Try using .eq() to cache h1 elements , .html() to return results; + operator to cast text to Number
// select all `h1` elements
var h = $("h1");
// results
var result = $("#result");
// first `h1`
var first = h.eq(0).text();
var second = h.eq(1).text();
result.html(function() {
var add = +first + +second;
var subtract = +first - +second;
return "Add first `h1` to second `h1`:" + add
+ "<br>Substract second `h1` from first `h1`:" + subtract
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<strong>$</strong><h1>1800</h1>USD<br>
<strong>$</strong><h1>800</h1>USD<br>
<br>
<div id="result"></div>
You retrieve the inner text of the HTML by using .text() and parse it as an integer using parseInt as the others above have explained.
You can then append it to your HTML after that.
Your HTML might look like this:
<div id="math">
<h1>800</h1>
<h1>1800</h1>
</div>
<h1 id="answer"></h1>
And your jquery like this:
var math = $("#math"); //Get the math element
var numbers = math.find('h1'); //Get all the numbers from the math div
var answer = $("#answer"); //Get the element
var total = 0;
numbers.each( function() {
total += parseInt( $(this).text() ); // Add each number together
});
answer.append( total ); // Append the total to the answer element
Here is a fiddle.
https://jsfiddle.net/75qxy57d/1/

Javascript Count numbers

This probably is a very easy solution, but browsing other questions and the internet did not help me any further.
I made a javascript function which will give me a random value from the array with its according points:
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
document.getElementById("Points").innerHTML += punten;
}
I've added a += punten so i can see that it works correctly. It shows me all the point in the div with the id Points.
But what i wanted to do is count it all together so if i were to draw a 4, King and a 10 it should show 24 instead of 41010.
Thanks in advance! And if you're missing any information please let me know
Currently you are just adding strings together, which concatenate (join together) hence why you end up with 41010. You need to grab the current innerHTML (total) and use parseInt() to convert from a string to a number, then add your new cards that have been chosen, then assign this new value to the innerHTML of your element.
Try the following
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1];
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
var total = curPoints + parseInt(punten, 10);
document.getElementById("Points").innerHTML = total;
}
More info on parseInt() here
EDIT
I've added this line -
var curPoints = parseInt(document.getElementById("Points").innerHTML, 10) || 0;
Which will try and convert the innerHTML of the "Points" div, but if it is empty (an empty string converts to false) then curPoints will be equal to 0. This should fix the issue of the div being blank at the start.
innerHTML is a string and JavaScript uses + for both string concatenation as numeric addition.
var pointsInHtml = parseInt(document.getElementById("Points").innerHTML, 10);
pointsInHtml += punten;
document.getElementById("Points").innerHTML = punten;
The second parameter 10 of the parseInt method is usually a good idea to keep there to avoid the function to parse it as an octal.
It might be easier to keep a points variable and only at the end put it in the #Points container, that would make the parseInt no longer necessary
innerHTML will be a string, so you need to convert it into an integer prior to adding the card value :)
function random_card(){
var rand = Math.floor(Math.random()*cards.length);
var html = "card: "+cards[rand][0]+"<br/>points: "+cards[rand][1]+"<br/><br/>";
document.getElementById("Player").innerHTML += html;
var punten = cards[rand][1],
curPunten = parseInt(document.getElementById('Points').innerHTML);
document.getElementById("Points").innerHTML = curPunten + punten;
}

2 text box need to verify they are not empty or contain 0

I have a function with info that grabs hours, rates, and then tax deduction and then spits it out. It works fine
var newtax= new Number(dep[i]);
taxrate = newtax*100;
var h=eval(document.paycheck.hours.value);
var r=eval(document.paycheck.payrate.value);
document.paycheck.feedback.value= taxrate + txt;
var total= r*(1-newtax)*h ;
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
I have to put where it takes the total and puts it in a function to put it only two decimals. It works this way and only does two decimals but i need the decimal conversion in a function. can anyone shed some like .
This is where i cut it to two decimals and i am unable to put in function and then send it back to the feedback3.value.
total=total.toFixed(2);
document.paycheck.feedback3.value= ("$ "+ total);
If you're asking how to write a function that takes a number and formats it as a dollar value with two decimals (as a string) then this would work:
function formatMoney(num) {
return "$ " + num.toFixed(2);
}
// which you could use like this:
document.paycheck.feedback3.value= formatMoney(total);
// though you don't need the total variable (unless you use it elsewhere)
// because the following will also work:
document.paycheck.feedback3.value = formatMoney( r*(1-newtax)*h );
By the way, you don't need eval to get the values from your fields. Just say:
var h = document.paycheck.hours.value;
var r = document.paycheck.payrate.value;

javascript parse float error

I am trying to get sum of rows of my table:
td1 val = $5,000.00; td2 val = $3000.00;
And I am using the following code:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html());
});
$('.total_num').html(totalnum);
This code works perfect if I remove money formatting from the number, otherwise it gives NaN as a result even if I am using parseFloat.
What am I missing?
Try:
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).html().substring(1).replace(',',''));
});
$('.total_num').html('$' + totalnum);
This will remove the $ (or whatever currency symbol) from the beginning and all commas before doing the parseFloat and put it back for the total.
Alternatively you could use the jQuery FormatCurrency plugin and do this:
totalnum+= $(this).asNumber();
If you add $ to the value, it is no longer an integer, and can no longer be calculated with.
Trying to make the formatted value back into a number is a bad idea. You would have to cater for different currency symbols, different formattings (e.g. 1.000,00) and so on.
The very best way would be to store the original numeric value in a separate attribute. If using HTML 5, you could use jQuery's data() for it:
<td class="num" data-value="1.25">$1.25</td>
....
var totalnum = 0;
$('.num').each(function(){
totalnum+= parseFloat($(this).data("value"));
});
$('.total_num').html(totalnum);
this way, you separate the formatted result from the numeric value, which saves a lot of trouble.
Try removing $ and any other character not part of the float type:
var totalnum = 0;
$('.num').each(function(){
var num = ($(this).html()).replace(/[^0-9\.]+/g, "");
totalnum+= parseFloat(num);
});
$('.total_num').html(totalnum);
Edit: updated replace to remove all non-numerical characters (except periods) as per this answer.

Categories