JavaScript function to add two numbers is not working right - javascript

My code in HTML takes a user input number in, and it does a calculation and then displays the output. The user chosen input is put into a formula and the result of the formula is added to the user input number, but when it adds the two number together it's adding a decimal spot.
For example, if the number 11 is chosen, the result of Rchange is 0.22, so .22 is then added 11 to be 11.22 for newResistance, but instead it is displaying the value as 110.22 instead.
function calc(form) {
if (isNaN(form.resistance.value)) {
alert("Error in input");
return false;
}
if (form.resistance.value.length > 32) {
alert("Error in input");
return false;
}
var Rchange = .01 * 2 * form.resistance.value;
var newResistance = (form.resistance.value + Rchange);
document.getElementById("newResistance").innerHTML = chopTo4(newResistance);
}
function chopTo4(raw) {
strRaw = raw.toString();
if (strRaw.length - strRaw.indexOf("0") > 4) strRaw = strRaw.substring(0, strRaw.indexOf("0") + 5);
return strRaw;
}

HTML DOM element properties are always strings. You need to convert them to numbers in your usage.
parseInt(form.resistance.value);
parseFloat(form.resistance.value);
+form.resistance.value;
(Any of the three will work; I prefer the first two (use parseInt unless you're looking for a float).)

Try newResistance = +form.resistance.value + Rchange;. This will convert it to a number.

It's because it's treating the values as a string.
form.resistance.value + Rchange are both strings, so it's appending it.
Use the parseInt JavaScript method to get the decimal version.

Related

Adding a number to a variable in a parent window

I am trying to load an existing answer and then add a number to it. The answerTotal variable has been set to the value of the recorded answer.
This then should be increasing by 12.5 each time the if statement actions. The problem is that this is not what is happening.
The number is being added on to the end of the loaded answer, for example if the load answer is 25, the output would be 2512.5 when it should be 37.5.
I have seen answers on here mentioning parseInt but it either doesnt work or im not using it correctly. parse answer
Here is what I have at the moment:
var answerTotal = 0;
window.parent.LoadAnswerReturned = function (Reference, Value) {
answerTotal = Value;
}
setTimeout(function(){
window.parent.LoadAnswer('TEST');
}, 100);
function checkAnswer(clicked) {
if(...){
...
answerTotal += 12.5
}
}
Please let me know if any more information is needed. Cheers.
It seems that the variable answerTotal is a string. You need to convert it to number using Unary Plus and then add it other number.
function checkAnswer(clicked) {
if(...){
...
answerTotal = +answerTotal + 12.5
}
}
The unexpected result is because by the type of the variable data that is string rather than number. This in turn means that string addition is performed:
"25" + "12.5" = "2512.5"
Instead, you should update you code to ensure arithemtic addition is performed instead:
function checkAnswer(clicked) {
if(...){
...
/* Use parseFloat to ensure two numbers are added, rather than a string
and a number */
answerTotal = Number.parseFloat(answerTotal) + 12.5;
}
}
You should parse your float variable, so you ensure you are using float variables:
answerTotal = parseFloat(answerTotal) + 12.5;

Convert specific value in a form to avoid 1.0 does not equal 1

I am currently trying to take all changes made to a form and put it into a JSON. If there are no changes than the JSON is empty. The form contains values that are strings, ints, and floats. So, I cannot cast them all as a specific type.
This wasn't an issue until I ran into the result form the console.log statement batchsize:string 1.0 does not equal string 1. Obviously this is correct in saying the two strings are not equal, but I am having trouble with finding a way that allows me to compare them without this being an issue. Does anyone have any advice
function getChanges()
{
//Get All User made changes form the website
var returnJSON = "{ ";
$('#form *').filter(' input:not([type="submit"])').each(function(){
var current = this.value;
var original = this.getAttribute('value')
var id = $(this).attr('id');
if((id!=="prod")&&(id!=="prodamt")&&(id!=="subtotal")&&(id!=="matlamt")&&(id!=="tax")&&(id!=="total")&&(id!=="matl")&&(id!=="prod-detail-formula-price")&&(id!=="prod-detail-formula-taxable")) //this ones for you zoe
if(current !== original)
{
returnJSON += '"'+id+'" : { "original":"'+original+'", "modified":"'+current+'"},';
console.log(id+":"+typeof original+ original +" does not equal " +typeof current+current);
}
});
returnJSON = returnJSON.substr(0, returnJSON.length-1);
returnJSON += '}';
return returnJSON;
}
use $.isNumeric() and if both are numeric check are they equal as a numbers using parseFloat or parseInt to convert to numeric

jquery comparing 2 integers

My submit click function is as below.
aAmt is a $ field like for eg. $45.00
a_amount is always 10000.
I am converting a_amount to $ in displayCurrencyFormat function.
I am then converting both to parseInt and doing >= comaprison and it fails. Even though aAmt is > $10000 and conition should display alert it doesnt.
$("#submitId").click(function () {
var aAmt = $("#aAmt").val();
var a_amount = "${dAmt}";
a_amount = displayCurrencyFormat(a_amount);
var pLen = $("#pOd").val();
if ((parseInt(aAmt) >= parseInt(a_amount)) && (pLen.length == 0)) {
$('#pDiv').text('Please provide a password');
$("#pOd").focus();
return false;
}
...//
});
function displayCurrencyFormat(a_amount)
{
//convert amount to currency format
var nbrAmt = Number(a_amount.replace(/[^0-9\.]+/g,""));
var fmtAmt = '$' + nbrAmt.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
return fmtAmt;
}
You should convert it into an integer-like data first, and then you can compare them.
The currency formatted input are considered as not a number format so comparing them are something like String to String comparison, not Number to Number like what you want to achieve.
Refrence link: How to convert a currency string to a double with jQuery or Javascript?
Do you know that parseInt('$10000') actually giving you "NaN"?
And as i can see here you are trying to compare integer and string...
Just try to alert aAmt and a_amount variables before you compare them and you will see what is actually going on...

Obtain numbers from a field and process them

I have a field which obtains it input through a list of links associated with numbers. (Similar to a calculator but without operators). I want to retrieve these numbers and put them through a function which divides them by 12. (A conversion from feet to inches).
First I have a list of jQuery click functions like this:
$('#a0').click(function(){
writeInput(input, one); // var one = 1;
});
Next I have the function "write Input" (This is where the numbers are displayed on a "screen")
function writeInput(field, str){
$input = $(field);
var text = $input.val($input.val() + str);
$input.text(text);
convert(text);
}
And lastly I have a function which is supposed to divide the number inputted by 12
function convert(input){
var divide = (input / 12);
$("#output").html(divide); //output is a paragraph where the number is displayed
}
When I run my code I am getting NAN output where the number should be. I have tried parseInt() and other tricks. But the closest I have come to something correct is when I got [object] [object] output.
Any help would be appreciated. Thanks!
In your code text is a jQuery object, you are using val as setter which returns a jQuery object, you should use val/text method as a getter for retrieving updated value.
function writeInput(field, str){
var text = $(field).val(function(i, v){
return v + str;
}).text(function(i, t){
return t + str
}).val();
convert(text);
}

How to append an extra 'Zero' after decimal in Javascript

Hye,
Iam new to javascript working with one textbox validation for decimal numbers . Example format should be 66,00 .but if user type 66,0 and dont type two zero after comma then after leaving text box it should automatically append to it .so that it would be correct format of it . How can i get this .How can i append ?? here is my code snippet.
function check2(sender){
var error = false;
var regex = '^[0-9][0-9],[0-9][0-9]$';
var v = $(sender).val();
var index = v.indexOf(',');
var characterToTest = v.charAt(index + 1);
var nextCharAfterComma = v.charAt(index + 2);
if (characterToTest == '0') {
//here need to add
}
}
Use .toFixed(2)
Read this article: http://www.javascriptkit.com/javatutors/formatnumber.shtml
|EDIT| This will also fix the issue if a user types in too many decimals. Better to do it this way, rather than having a if to check each digit after the comma.
.toFixed() converts a number to string and if you try to convert it to a float like 10.00
then it is impossible.
Example-
10.toFixed(2) // "10.00" string
parseFloat("10.00") // 10
Number("10.00") // 10

Categories

Resources