Wrong Math Algorithm with javascript? - javascript

im trying to make some Algorithm function with javascript and get some problems
function Algorithm() {
var endone;
var endtwo;
var endtheend;
var v1 = document.getElementsByName("v1")[0].value; //worth to 91
var v2 = document.getElementsByName("v2")[0].value; //worth to 61
var v3 = document.getElementsByName("v3")[0].value; //worth to 20
endone = Math.round(v1 * 0.30);
endtwo = Math.round(((v2 + v3) / 2) * 0.70);
endtheend = endone + endtwo;
document.getElementById("ending").innerHTML = "end : " + endtheend;
}
if im doing the same Algorithm with a calculator im getting 55.65 , but when im trying to use this function somehow im getting 2169.
someone might know what is the problem and show me how to solve her?

The problem is that v1, v2 and v3 are not numbers. They are strings. So each calculation you make is relies on implicit conversions and operations between strings.
For instance, in the following snippete we have an implicit conversion of the the string value "91" to a double floating number and then the usual mulitplication is done.
var v1 = "91";
console.log(v1*0.3);
On the other hand below:
var v2 = "61";
var v3 = "20";
console.log((v2 + v3) / 2)
We have a string concatenation "61"+"20" results in a new string "6120" and then "6120" is implicitly converted to a double floating number and the division with 2 is done.
What's the solution ?
You have to parse these values either by using parseInt or parseFloat, like below:
var v2 = "61";
var v3 = "20";
console.log((parseInt(v2,10) + parseInt(v3,10)) / 2)

When you get an HTMLInputElement's value property, what you get is a string.
And the + operator applied to two strings merely concatenates them, so if for instance v2 == "7" and v3 === "0", when you do (v2 + v3), you'll get "70".
The solution to your problem is to simply pass the values through parseInt:
var v1 = parseInt(document.getElementsByName("v1")[0].value, 10);
var v2 = parseInt(document.getElementsByName("v2")[0].value, 10);
var v3 = parseInt(document.getElementsByName("v3")[0].value, 10);
// The second argument to parseInt isn't needed if you only target newer browsers.
I'd suggest you read up on type coercion in JavaScript for more info.

The issue is all of your values (v1, v2, v3) are String type. You need to convert them into Number first. So the following code should work :
function Algorithm() {
var endone;
var endtwo;
var endtheend;
var v1 = Number(document.getElementsByName("v1")[0].value);
var v2 = Number(document.getElementsByName("v2")[0].value);
var v3 = Number(document.getElementsByName("v3")[0].value);
endone = Math.round(v1 * 0.30);
endtwo = Math.round(((v2 + v3) / 2) * 0.70);
endtheend = endone + endtwo;
document.getElementById("ending").innerHTML = "end : " + endtheend;
}
you can also use parseInt if your value contains any alphabetic characters.

Related

Javascript extract last numbers from Math.random

So I'm trying to do a script for Photoshop with javascript and I can't get the last 6 number from a Math.random.
I tried using the same code as in Strings with "randomID.substr(randomID.length - 6);" or "randomID.substr(-6);" but that didn't work.
var kodi = 'FJ0B';
var randomID = Math.floor(Math.random() * (999999999999 - 100000000000 + 1) + 100000000000);
var lastSix = randomID.toFixed(-6);
var kontrataLayer = (kodi.charAt(0) + lastSix);
Math.floor works fine, I need it with 12 digits for another function.
Thank you.
What about:
var randomIDString = randomID.toString();
var lastSix = Number(randomIDString.substr(randomIDString.length - 6));
For substr to work you need to convert the number to a string. Maybe that's why it didn't work for you earlier?

Google App Script - How to use methods without defining their object

I am writing the script behind a spreadsheet that has lots of durations on it in the format of (##:##.##) (ex 12:43.76). I need to write some code that converts this to just seconds. I wrote code that did the opposite, made seconds into that format. But when writing a custom formula for this, the .split method does not work.
function MTOS(input){
String(input);
if (typeof(input) != "string") {
Logger.log("Not a string")}
var array = input.split(":");
Logger.log('The original string is: "' + input + '"');
var min = Number(array[0]);
var sec = Number(array[1]);
Logger.log("min=" + min);
Logger.log("sec=" + sec);
var MIN = min*60;
Logger.log(MIN);
var ex = MIN+sec;
Logger.log(ex);
return ex;
}
This is what I have in the script editor. The input is the parameter from the spreadsheet when I write the formula in the sheet itself (ex - =MTOS(3:23.53)). When I run the function in the script editor, it gives me the error "TypeError: Cannot call method "split" of undefined. (line 5, file "MTOS")" and in sheets, it returns "Error : Result was not a number." I understand that this is happening because input is not defined in the function itself, so .split cannot work. But how else can I write the custom formula for sheets?
Thank you.
This seems to work for me: (Perhaps I'm misunderstanding the question).
function MTOS(input){
var iA = input.split(":");
var min = Number(iA[0]);
var sec = Number(iA[1]);
Logger.log('Seconds=%s',min * 60 + sec);
}

get wrong result function jquery javascript

I am using the following script. But I am receiving a wrong result for x_b_bbetrag.
When do an calculation exp 100/108 I get 9.92 instead of 92.59.
What am I missing here?
Code below:
var betrag = 100
var kurs = 1
var minkl= 1
var msatz= 0.08
$("#x_b_betrag").change(function() {
var betrag = $("#x_b_betrag").val();
var kurs = $("#x_b_kurs").val();
var minkl =$("input[name='x_b_mwstinkl']:checked").val();
var msatz =$("input[name='x_b_mwst']:checked").val();
if (minkl == "1"){
$("#x_b_rechenbetrag").val((betrag * kurs).toFixed(2));
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + msatz) ).toFixed(2));
}
Use parseFloat
multiplication, division and subtraction automatically parse string to number. for summation you need to parse it.
$("#x_b_bbetrag").val( ( (betrag * kurs) /(1 + parseFloat(msatz) ) ).toFixed(2));
///1 + "1" = 11 not 2
Parse your inputs into numbers.
For example :
var betrag = parseFloat($("#x_b_betrag").val());
MDN on parseFloat
The value of the msatz variable is not 0.08 but "0.08". It's a string, so when you add one to it, the number will be converted to a string so that they can be concatenated, and the result is "10.08" not 1.08. The string will implicitly be converted to a number when you use it in the division, as it's not possible to divide by a string.
Parse the string into a number:
var msatz = parseFloat($("input[name='x_b_mwst']:checked").val());

Javascript number/string issue

I am working with an application called TEC-IT Wedge to interface with a grocery scale (for those not in the know a grocery scale is a glorified scale with a scanner.
The scale is connected to a serial port on the PC and thw wedge app monitors that port, the code below handles the scan of the barcode then requests the weight, all of this is working.
Where I am running into the issue is formating the returning weight from the scale.
the data returned from the scale is in the format of ASCII "S11####" so S110004 would be for an item weighing 0.04 pounds and this is how I need to send that wait to the application that we are using the scale to enter data with. For the code below a return of S110004 it returns 00.4
I think I am loosing 0's in the grab of the digits for some reason to place the decimal poit in the correct position.
var cartonverify = Left(DATARAW, 5);
var weightverify = Left(DATARAW, 3);
if (cartonverify == "S08B3")
{
ActivateWindow("Untitled - Notepad");
SendKeyStrokes(DATARAW.replace(/^S08B3+/i, '') );
DATA = "";
WriteToDevice("S11\x0d", 1000);
}
if (weightverify == "S11")
{
ActivateWindow("Untitled - Notepad");
var cartwieght = Right(DATA, 4);
if (cartwieght.length == 4)
{
var cartounces = Right(cartwieght, 2);
var cartpounds = Left(cartwieght, 2);
var WMWeight = cartpounds + "." + cartounces;
SendKeyStrokes(WMWeight);
DATA = "";
}
}
Re-form your string to something that can be parsed as a number as desired.
var str = 'S110004';
str = str.replace(/S11(\d\d)(\d\d)/, '$1.$2'); // "00.04"
var num = parseFloat(str); // 0.04
Putting the decimal place in at the RegExp step also saves you from having to use division.

Addition not working in Javascript

I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.

Categories

Resources