return '+' +n if positive number - javascript

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)

Related

cut the percentage from the variables

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)

Variable value changes once operators are applied

When I run this function with the first radio button selected, the system outputs the correct value of 30. However, once I try to apply some changes to this value (for example by adding 1 to this value of 30) the system shows me 301 as a result.
I get the same issue when the radio button with value 25 is selected. Once I try to do mathematical changes, the system treats this variable as 250.
Any ideas what I am missing here? Thanks in advance.
<script>
function f1()
{
...
var Ergebnis_RP = document.getElementsByName("Ergebnis_RP");
if(Ergebnis_RP[0].checked)
{ var Erg = Ergebnis_RP[0].value;}
else if(Ergebnis_RP[1].checked)
{ var Erg = Ergebnis_RP[1].value;}
...
document.write(Erg);
var Spielwert = Erg + 1;
document.write(Spielwert);
}
</script>
<body>
<input type="radio" name="Ergebnis_RP" value=30>Verl. Schwarz
<input type="radio" name="Ergebnis_RP" value=25>Verl. U3
</body>
The value of a textbox is always a string. You need to coerce it to a number. The easiest way to do that is:
+Ergebnis_RP[0].value
Be sure to do this every time you read a number from a textbox.
Further explanation of the issue:
When you combine two strings, they are concatenated like "ab" + "cd" -> "abcd".
But when you combine different types, the second one is coerced to be the same as the first. "ab" + 1 -> "ab" + "1" -> "ab1".
Your code takes a string and adds a number. The string happens to be digits but that doesn't matter. "12" + 3 -> "12" + "3" -> "123".
To fix this, start with a number then add the string. 0 + "12" -> 0 + 12 -> 12.
As a shortcut, the + operator acts on numbers just like the - operator. Consider the number -5. The - is a negation. + is another unary operator that takes a number and returns the same number. Sounds useless, but it has its place. +"12" -> 12.

jQuery filtering negative numbers and making them positive

I'm trying to produce a position change table which finds values less than zero, makes those values red, adds a class to activate a down arrow, and removes the minus sign from the negative values.
Everything works except I can't remove the minus sign. I have tried multiplying by -1 and Math.abs(), but nothing works. I'm not getting errors in the console either.
The values are being populated from csv data.
$('.move').filter(function() {
var neg = $(this).text() < 0;
return Math.abs(neg);
}).css( "color", "#ff0000" ).addClass('down');
Any help would be greatly appreciated.
Did you tried explicitly parsing the $(this).text() to a number, using parseInt?
Edit:
By the way, your filter is wrong you should do
$('.move').filter(function() {
var number = $(this).text();
var isNeg = number < 0;
$(this).text(isNeg ? Math.abs(number) : number);
return isNeg;
}).css( "color", "#ff0000" ).addClass('down');
You should parse the text returned by text() first using parseInt (to convert the string value into a number):
$('.move').filter(function() {
// This filter function will keep only negative integers
var val = parseInt($(this).text(), 10);
return !isNaN(val) && val < 0;
}).css( "color", "#ff0000" ).addClass('down');
If you want to remove the negative sign, you'll need to change the text of every element that passed your filter function. However, removing the '-' sign will change the behavior of your filter function if run twice or more (negative numbers now appear as positive numbers), so beware of that.
... .addClass('down').each(function () {
$(this).text($(this).text().replace('-', ''));
});

javascript testing if a value is a number AND a number greater than 0

I have an object property that may or may not contain a number and that number may or may not be equal to 0. For the moment, I have this:
var TheVar = parseInt(SomeObject.SomeVar, 10);
if (!TheVar > 0) {
TheVar = "-";
}
I want TheVar to be either a positive number or "-". I'm just wondering if my conditional statement is going to cover every case?
Thanks for your suggestions.
No. You are missing parentheses.
if( !(TheVar > 0))
NaN > 0 returns false, so the if condition will go through.

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