var return to NaN instead of number - javascript

Hey so i've something like that
var zxc1 = 1846;
var zxc2 = 1649;
var zxc3 = 174;
var zxc4 = 27;
if(message.toLowerCase() == ('!asd')) { client.say(channel, `zxc1` +`(${+ zxc1.toLocaleString()})` +` | zxc2 `+`(${+ zxc2.toLocaleString()})` +` | zxc3 ` +`(${+ zxc3.toLocaleString()})` +` | zxc4 ` +`(${+ zxc4.toLocaleString()})` +` | :) `);}
After typing !asd:
Result : zxc1(NaN) | zxc2 (NaN) | zxc3 (174) | zxc4 (27) | 2
what's the problem?
Why is zxc3 and zxc4 working but zxc1 and zxc2 no

In ${+ zxc1.toLocaleString()} the + will be applying on the result of zxc1.toLocaleString() to coerce it back to a number (which seems counterproductive).
If you are not sure if something is a number I do recommend you use the number function e.g. ${Number(zxc1).toLocaleString()} rather than using +
The reason why 3 and 4 are working is because (most likely) your locale adds a thousands separator and so 1 and 2 are not castable back to numbers directly

Related

Displaying a currency from a number

How can I change a number ( integer ) into a currency format while live input/typing?
ex :
45678 => 456.78
or
234567 => 2345.67 or 2,345.67 or 2 345.67
( depending on the mask format used )
Before people start tagging this question as an existing one, I have already seen the existing codes that format numbers, but those examples do not handle the last two numbers as decimals. Instead those format the string 45678 into 45 678.00 or 45,678.00 instead of 456.78.
Something like convert:
######## into ### ###.##
You could iterate the mask and reassemble the result string.
It creates from both values two arrays (with spread syntax ...) for a single number or mask character in an array.
Then it iterates the mask characters from the right side and
(m === '#' ? v.pop() || '' : v.length ? m : '') + s
builds a new string with either a numerical value, if # is found
m === '#' ? v.pop() || ''
or takes the value of the mask by checking the length of the values
v.length ? m : ''
to prevent adding spaces or unwanted characters.
function convert(i, mask) {
var v = [...i.toString()];
return [...mask].reduceRight((s, m) => (m === '#' ? v.pop() || '' : v.length ? m : '') + s, '');
}
console.log(convert(45678, '### ###.##')); // 456.78
console.log(convert(234567, '### ###.##')); // 2345.67
console.log(convert(234567, '###,###.##')); // 2,345.67
console.log(convert(234567, '### ###.##')); // 2 345.67
Add an event handler for when you type into the input to format the value for that input.
$('#myTextbox').keyup(function(){
$(this).val(($(this).val() /100).toFixed(2);
});
(number).toFixed() function converts a number to string. To avoid this try:
var x4 = 999546765687;
x4 = x4/100;
x4.toFixed(2);
Number(x4)
The toLocaleString() method returns a string with a language sensitive representation of this number.
var currency = 234567/100;
var currencyString = currency.toLocaleString('en-US')
console.log(currencyString);
For angular
https://angular.io/api/common/CurrencyPipe
Try using
#Component({
selector: 'currency-pipe',
template: `
A: {{a | currency}}
<!--output 'CA$0.26'-->
<p>A: {{a | currency:'CAD'}}</p>
<!--output 'CAD0.26'-->
<p>A: {{a | currency:'CAD':'code'}}</p>
<!--output 'CA$0,001.35'-->
<p>B: {{b | currency:'CAD':'symbol':'4.2-2'}}</p>
<!--output '$0,001.35'-->
<p>B: {{b | currency:'CAD':'symbol-narrow':'4.2-2'}}</p>
<!--output '0 001,35 CA$'-->
<p>B: {{b | currency:'CAD':'symbol':'4.2-2':'fr'}}</p>
</div>`
})
export class CurrencyPipeComponent {
a: number = 0.259;
b: number = 1.3495;
}

Replace inner html with value of html time a value using JQuery

I am working with an HTML table structure that contains values of text and integer. My goal is to identify which cells contain integer values and replace them with their value times -1. For instance:
This Year | 5 | 4 | -12
Last Year | 2 | 2 | 20
Would be updated to:
This Year | -5 | -4 | 12
Last Year | -2 | -2 | -20
Ideally, I would accomplish this with one line of JavaScript/jQuery. The line I am working with is:
$(".value-cell").filter(function( index ) {return $.isNumeric($(this).text());}).text(parseFloat($(this).text())*-1);
However, this line just fills the cells with NaN. I have tried a few variations of this but have not been able to accomplish what I am looking for.
UPDATE:
I should note, the filtration is working as expected and hitting the cells I want it to. I believe the problem lies with accessing $(this) in the text assignment, however, I am unsure of how else to access the text of the HTML element to multiply by -1.
Pass a function to .text() to have it operate on each element.
$(".value-cell").filter(function(index) {
return $.isNumeric($(this).text());
}).text(function(i, txt) {
return parseFloat(txt) * -1;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=value-cell>abc</div>
<div class=value-cell>123</div>
And if you don't need the filtered set after this, you can get rid of the .filter() call and make the new value conditional.
$(".value-cell").text(function(i, txt) {
return $.isNumeric(txt) ? parseFloat(txt) * -1 : txt;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=value-cell>abc</div>
<div class=value-cell>123</div>
And of course, a modern syntax solution with no jQuery dependency could look like this:
for (const el of document.querySelectorAll(".value-cell")) {
const t = el.textContent;
el.textContent = !t || isNaN(t) ? t : +t;
}
<div class=value-cell>abc</div>
<div class=value-cell>123</div>

How Do I Use Both Math.max() and Math.min() to bound my dragger

I'm building a horizontally dragging page layout. There are 3 columns, with two dragging objects. Everything is working fine except setting a max/min value for the drag.
The layout looks like this, with the two dragging bars either side of colB.
---------------------------
colA | colB | colC
| |
| |
| |
| |
| |
| |
| |
| |
I need to set it so that colA's dragger's maximum width (which is its left value) is equal to colC's dragger. Likewise, ColC's minimum needs to be colA's draggers' left value.
The function looks like this:
function doDragA(e) {
dragA.style.left = (e.clientX) + 'px';
}
function doDragC(e) {
dragC.style.left = (e.clientX) + 'px';
}
and I'm trying to do something like this:
function doDragA(e) {
var posC = parseInt(document.defaultView.getComputedStyle(dragC).left, 10);
dragA.style.left = (math.max(posC), math.min(0)) e.clientX + 'px';
}
function doDragC(e) {
var posA = parseInt(document.defaultView.getComputedStyle(dragA).left, 10);
dragC.style.left = (math.max(0), math.min(posA)) e.clientX + 'px';
}
But i'm getting syntax errors. I've console logged the values and they come through, it's just the math max/min syntax I'm getting wrong.
Firstly javascript is case sensitive, and the math object is Math, not math.
Secondly, the usage of min and max is to supply a list of arguments, not just one - it returns the answer to 'what is the value of highest/lowest of these?'.
Assuming you want the value of e.clientX bounded by some values valueMax and valueMin:
var valueUpToMax = Math.min(valueMax, e.clientX);
var valueAtLeastMin = Math.max(valueMin, e.clientX);
// so we can combine those to bound on both sides:
var boundedValue = Math.max(valueMin, Math.min(valueMax, e.clientX));
It seems like they should be the other way around; we limit to a maximum value by using Math.min, but it's because we are limiting to a maximum not trying to get a maximally high number.
The general principle is to use functions like in math:
c = f(a, b);
e = g(c, d);
-> e = g( f(a, b), d);

Why this bitwise operation is failing in Javascript

Some one please shed light on this when doing bitwise operation in javascript I get:
65527|34359738368 =>65527
Is it possible to handle this in javascript ?
From mysql command line:
select 65527|34359738368 ;
+-------------------+
| 65527|34359738368 |
+-------------------+
| 34359803895 |
+-------------------+
And more importantly its less than 2 ^ 36
select (65527|34359738368)< pow(2,36);
+--------------------------------+
| (65527|34359738368)< pow(2,36) |
+--------------------------------+
| 1 |
+--------------------------------+
What I read from this SO Q is that int in javascript support max 2^53 value. I might be missing sth
You linked to the answer yourself:
Note that the bitwise operators and shift operators operate on 32-bit ints.
As Tim has already pointed out, bitwise operations in JavaScript use 32-bit numbers. One solution (and probably the easiest) is to use a bignum library that supports bitwise operations, such as this one: https://www.npmjs.org/package/bignum.
Another way to do it would be to break the number into words, and do the operations on the words separately, old-school style:
var a = 65527;
var b = 34359738368;
var wordSize = 4294967296; // 2^32
var ah = Math.floor(a/wordSize);
var al = a - ah*wordSize;
var bh = Math.floor(b/wordSize);
var bl = b - bh*wordSize;
var xh = ah | bh;
var xl = al | bl;
var x = xh*wordSize + xl;
All we're doing is breaking the two operands into two words (high and low), doing the operations on the words, yielding our result (x) as a high and a low word, then recombining them to make a word.
You could, of course, bundle this into a neat function:
function or64(a,b){
var w64 = 18446744073709552000; // 2^64
var w32 = 4294967296; // 2^32
if(a>w64 || b>w64)
throw new Error('operands cannot exceed 64 bits');
var ah = Math.floor(a/w32);
var al = a - ah*w32;
var bh = Math.floor(b/w32);
var bl = b - bh*w32;
return (ah|bh)*w32 + (al|bl);
}
Now (in year 2020) you can also use BigInt which since ES2020 is a standard built-in object. BigInt can be used for arbitrarily large integers.
The easiest way to convert a standard Number to BigInt in JavaScript is to append "n" to it. Like this:
65527n|34359738368n => 34359803895n
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt for more information

The if statement doesnt work in my forloop

Currently I am working on Java script project.the project is for Checking the values selected from a UDDF file with the whole values in the UDDF file.But the if statement used for comparison is not working.I have put my code below
function parseUddf(){
var myArray=new Array("null","airportID","airportSiteNo","faaRgn","uddfVer","null","airportName","verificationDate",
"city","state","horizontalelevationdatum","horiAccuracy","elevAccuracy","orthoDatum","orthoAccuracy",
"magDec","verificationDate","airportOrthoElev","airportEllipsoidElev","airportElevationLoc",
"verificationDate","towerFloorOrthoElev","towerFloorEllipElev","verificationDate","arpLatitude","arpLongitude");
var selt=document.getElementById("textdis").value;
var x = document.getElementById("uddf").value;
x = x.split("#");
var x0 = x[0];
x0 = x0.split("|");
var j=x0.length;
alert(j);
for(var i=1;i<x0.length;i++){
alert("selt="+selt.toString());
if(selt.toString()==x0[i])
{
alert("success");
alert("i="+i);
alert(myArray[i]);
//document.getElementById("textdistitleid").value=myArray[i];
break;
}
}
}
the UDDF file values are:
|FAI |50219.A |AAL |1.07|
|FAIRBANKS INTERNATIONAL AIRPORT |1592011|
|FAIRBANKS |ALASKA |
|NAD83 |5 CM |15 CM |NAVD88 |25 CM |
|-20.4|1592011|
| 439.0| 470.0|20R+3990|1592011|
| 529.0| | |
| 644854.4|-1475123.2|
I need your help
Instead of using == you can use .equals():
selt.toString().trim().equals(x0[i].trim())
You can get your trim() function for javascript from here

Categories

Resources