cut the percentage from the variables - javascript

I check the cell for a blank in the database. If it's not empty, I cut off 5 percent, if not, I skip it, but I have a problem. Maybe I'm not checking for emptiness. I have after null ? '' brackets are going and they my percent stops working and outputs me just 10-2.
let one = User[0].percent // - 10% (variable one value: 100)
let two = checkingOptions.options == null ? '' : -5 // - 5%
let three = checkingFly[2] == null ? '' : - checkingFly.percent // - 2%
let mp = + one + two + three
console.log(mp)
I want him to calculate for me correctly
10-2 = 8,
But I don't know how I can do it.

The + operator is overloaded - for numbers it does addition, for strings it does concatenation. And for mixed values it coerces them to be the same type one way or the other.
One or more of your values are probably strings. Figure out which ones are strings and convert them like this:
const allPercent = Number(User[0].percent)

Related

How does javascript do the comparison?

I have an object array that gets new values every time a new user is created. I need to do some search based on the person name and then do some operations with it and I implemented a binary search and in my code that I found in the internet but theres something thats bothering me with the search code.
The object looks as follows:
person = {
name: name,
password: password,
cartItems: '',
cartPrice: 0
}
then I push it to an array.
and the binary search code looks as follows:
searchValues(users, value) {
var startIndex = 0,
stopIndex = users.length,
middle = Math.floor((stopIndex + startIndex) / 2);
while(users[middle].name != value && startIndex < stopIndex){
//adjust search area
if (value < users[middle].name) {
stopIndex = middle - 1;
} else if (value > users[middle].name) {
startIndex = middle + 1;
}
//recalculate middle
middle = Math.floor((stopIndex + startIndex) / 2);
}
return (users[middle].name != value) ? -1 : middle;
}
My questions is: How does JavaScript do the comparison between string values, does it convert to ascii? I can understand the code if it was applied to numbers but I'm a bit confused when it comes to strings.
Thank you in advance for anyone willing to help
EDIT: I forgot to mention that i've sorted my array before hand.
The algorithm to compare two strings is simple:
Compare the first character of both strings.
If the first character from the first string is greater (or less) than the other string’s, then the first string is greater (or less) than the second. We’re done.
Otherwise, if both strings’ first characters are the same, compare the second characters the same way.
Repeat until the end of either string.
If both strings end at the same length, then they are equal. Otherwise, the longer string is greater.
reference find more detail here

Decimal Comparison without rounding in javascript

I have 2 textboxex for decimal values and I need to compare them in JavaScript. The scenario is
var first = $('#txtFirst').val();
var second= $('#txtSecond').val();
In textboxex I'm entering following values
first => 99999999999998.999999997
second => 99999999999998.999999991
I tried the below code
if (parseFloat(parseFloat(first).toFixed(10)) <= parseFloat(parseFloat(second).toFixed(10)))
This returns true because it rounds it so both the values becomes 99999999999999. How to fix it?
Just compare without converting into integer
var first = $('#txtFirst').val();
var second= $('#txtSecond').val();
if ( first == second )
{
// they are equal
}
if you want to compare upto 10 decimals then
var first10Decimals = first.split(".").pop().substring(0,10);
var second10Decimals = second.split(".").pop().substring(0,10);
if ( first10Decimals == second10Decimals )
{
//they are equal
}
Vanilla JavaScript can't handle such big numbers. You should use something like big.js that is designed to work with arbitrary large numbers :
GitHub : https://github.com/MikeMcl/big.js/
Documentation : https://mikemcl.github.io/big.js/

return '+' +n if positive number

I have this following one-liner.
data = ({id:x.toString(),text: x.toFixed(2)} for x in [params.min..params.max] by params.step)
the parent function takes in a max, min, and step. It creates options in a combobox through this. IE, [10, 1, 10] would leave me with an option box with 20 selections: -10..0..10.
This works fine, but I need to display a '+' when the number is positive. I can't, for the life of me, figure out, syntactically, where to put this conditional. Any advice?
Just use a conditional expression. CoffeeScript if...then...else blocks can be used as expressions, so the following expression
(if x > 0 then '+' else '') + x
would produce a + sign if the number is positive.
You can simply insert that into your existing code like so:
data = ({ id: x.toString(), text: (if x > 0 then '+' else '') + x.toFixed(2) } for x in [params.min..params.max] by params.step)

JavaScript IF statement evaluating TRUE incorrectly - why?

I have a very, very simple logical test of the number of licenses a customer has purchased vs. the number they have used:
else if(utype == "3"){
var tech_lic = $("#technician_lic").val();
console.log('tech lic = ' + tech_lic)
var tech_allow = $("#technician_lic_allow").val();
console.log('tech allow = ' + tech_allow)
if(tech_lic >= tech_allow)
{
alert("You must purchase more licenses to create this Technician");
return false;
}
I threw in the console.log statements trying to debug this - normally they aren't there.
Console.log when I click "add" button:
tech lic = 4 application.js:262
tech allow = 100 application.js:264
Then we hit "You must purchase more licenses" alert in the window.
WHAT THE HECK?
How can 4 >= 100 evaluate true?
Because .val returns a string. '4' is indeed greater than or equal to '100'. Cast the values to numbers first (if you know that they are always numbers for the purposes of this comparison).
if (+tech_lic >= +tech_allow)
You are evaluating them as strings, so "4" IS greater than "100".
You will need to cast them as integers before comparison:
var tech_lic = parseInt($("#technician_lic").val(), 10);
var tech_allow = parseInt($("#technician_lic_allow").val(), 10);
The string "4" is greater than "100", whereas the number 4 is less than 100.
It's not that 4 >= 100 is true, it's that "4" >= "100" is true.
The values that you get are strings, so they will be compared lexically, not numerically.
Parse the values into numbers:
var tech_lic = parseInt($("#technician_lic").val(), 10);
var tech_allow = parseInt($("#technician_lic_allow").val(), 10);
Do this way:-
if(Number(tech_lic) >= Number(tech_allow))
{
// Do your stuff
}

How to increment a numeric string by +1 with Javascript/jQuery

I have the following variable:
pageID = 7
I'd like to increment this number on a link:
$('#arrowRight').attr('href', 'page.html?='+pageID);
So this outputs 7, I'd like to append the link to say 8. But if I add +1:
$('#arrowRight').attr('href', 'page.html?='+pageID+1);
I get the following output: 1.html?=71 instead of 8.
How can I increment this number to be pageID+1?
Try this:
parseInt(pageID, 10) + 1
Accordint to your code:
$('#arrowRight').attr('href', 'page.html?='+ (parseInt(pageID, 10) + 1));
+ happens to be valid operator for both strings and numbers that gives different results when both arguments are numeric and when at least one is not. One of possible workarounds is to use operator that only have numeric context but gives same mathematical result, like -. some_var - -1 will always be same as adding 1 to some_var's numeric value, no matter if it is string or not.
$('#arrowRight').attr('href', 'page.html?='+ (pageID - -1));
All these solutions assume that your number you want to add 1 to is within the machine precision for an integer. So if you have a large enough number within that string when you add 1 to it won't change the number.
For Example:
parseInt('800000000000000000', 10) + 1 = 800000000000000000
So I wrote a quick solution to the problem
function addOne(s) {
let newNumber = '';
let continueAdding = true;
for (let i = s.length - 1; i>= 0; i--) {
if (continueAdding) {
let num = parseInt(s[i], 10) + 1;
if (num < 10) {
newNumber += num;
continueAdding = false;
} else {
newNumber += '0';
}
} else {
newNumber +=s[i];
}
}
return newNumber.split("").reverse().join("");
}
Now, using the same example above
addOne('800000000000000000') + 1 = '800000000000000001'
Note that it must stay as a string or you will lose that 1 at the end.
It needs to be a integer, not a string. Try this:
pageID = parseInt(pageID)+1;
Then you can do
$('#arrowRight').attr('href', 'page.html?='+pageID);
Simply, $('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The parentheses makes the calculation done first before string concatenation.
let pageId = '7'
pageId++
console.log(pageId)
Nowadays, you just need to pageID++.
Just change your order of operations by wrapping your addition in parentheses; if pageID is already a number, parseInt() isn't necessary:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
Demo
As long as your pageID is numeric, this should be sufficient:
$('#arrowRight').attr('href', 'page.html?='+(pageID+1));
The problem you were seeing is that JavaScript normally executes in left-to-right order, so the string on the left causes the + to be seen as a concatenator, so it adds the 7 to the string, and then adds 1 to the string including 7.

Categories

Resources