I'd like to sum up to two (string) values.
The values come from a data layer. I know how to get the data out of the data layer,
return datalayer.path123.infoABC;
but I don't know how to sum them with JS.
All input is appreciated!
The value with the quotes is the String "1" where as the value without the quotes is the number 1. If you add those together the answer will be the String "11".
If you want to get the sum as a number you first need to convert the String into a number. You can do this by passing it to the Number() function. Since I don't know which is the string in your case I'll just conver both to a number to be safe.
var a = Number(datalayer.path123.infoABC);
var b = Number(datalayer.path123.infoDEF);
var sum = a + b;
Related
In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)
I am new to using D3.js and I am having problems converting string data into a number. I am using a CSV with one column called "Belgium" composed by numbers like these ones: 54,345 or 1,234,567.
I tried to convert them into numbers by using
data.forEach(function(d) {
d.Belgium = +d.Belgium;
}
but I get NaN as a result. I also tried using
d.Belgium = parseInt(d.Belgium);
but it takes the figures before the first comma and removes the rest of the number. For example, if one number is 1,234,562, using parseInt() I just get 1. If the figure is 982,381, it remains 982.
Remove all , with string.replace(searchvalue, newvalue):
parseInt(str.replace(/,/g, ""))
so for example:
console.log(parseInt("1,234,562".replace(/,/g, "")))
As noted below, use parseFloat instead of parseInt if your numbers may contain decimals e.g. 3.141,592 to keep the floating point number.
I took a bit of a different approach. I used .split(",") to split the value into an array at every ,, then used .join("") to join each index of the array with empty spaces. Used the + operator for ease of use but could have been parseFloat() as well.
let stringNumber = "1,250,234.093";
let numStringNumber = +stringNumber.split(",").join("");
console.log(numStringNumber);
console.log(typeof numStringNumber);
I am trying to parse a hex value to decode a card
The hex data I receive from the card is f8b2d501f8ff12e0056281ed55
First I am converting this to an integer with parseInt()
var parseData = parseInt('f8b2d501f8ff12e0056281ed55', 16);
The value recieved is 1.9703930145800871e+31
When I try to decode this using the bitwise operator in Javascript
var cardNumber = ((parseData & 0xFFFFF) >> 1).toString();
I received a 0 value.
What am I doing wrong here, how can I parse the value of such large integer number?
There are two ways to do it:
First, notice that & 0xFFFFF operation in your code is just equivalent to getting a substring of a string (the last 5 characters).
So, you can just do a substring from the end of your number, and then do the rest:
var data = 'b543e1987aac6762f22ccaadd';
var substring = data.substr(-5);
var parseData = parseInt(substring, 16);
var cardNumber = ((parseData & 0xFFFFF) >> 1).toString();
document.write(cardNumber);
The second way is to use any big integer library, which I recommend to you if you do any operations on the large integers.
Since the number integer is so big you should use any bigNum library for js.
I recommend BigInteger, since you are working only with integers and it supports bitwise operations, however you can also check this answer for more options.
There are a few Javascript functions available to convert anything into its equivalent number. Number() operates on an Object, valueOf(), parseFloat, parseInt() are also available.
I have an array which stores numbers 0-9 and decimal point, the elements of the array taken together represents a number. What is the best way to convert this array into a number, whole or fractional?
EDIT: Apologies if I were not clear before. The array, holding the 0-9 characters and possibly a decimal point, could represent either a whole number(without the decimal obviously) or a fractional number. So please suggest something that works for both cases. Thanks.
Try this
var a = [1,2,3,".",2,3];
var num = +a.join("");
What is the best way to convert this array into a number, whole or fractional?
Firstly to combine your array elements you should use Array.join().
You will then have a concatenated variable of your values and decimal. To convert this to a whole number, use parseInt(), and to a floating point number use parseFloat(). You can use the unary + operator (which acts similarly to parseFloat), however in my opinion it is not the best choice semantically here, as you seem to want a specific type of number returned.
Example:
var arr = ['1','.','9','1'];
var concat = arr.join();
var whole = parseInt(concat);
var floating = parseFloat(concat);
Also, parseInt will trim the decimal portion of your number, so if you need rounding you can use:
var rounded = Math.round(parseFloat(concat));
You could use the split property of the string. It splits all the characters into an zero based array.
var charSplits = "this is getting split.";
var splitArr = charSplits.split();
Console.log(splitArr);
// this returns i
Console.log(splitArr[2]);
I get 28.6813276578 when i multiply 2 numbers a and b, how can i make it whole number with less digits
and also, when i multiply again i get results after first reult like 28.681321405.4428.68 how to get only one result ?
<script>
$(document).ready(function(){
$("#total").hide();
$("#form1").submit(function(){
var a = parseFloat($("#user_price").val());
var b = parseFloat($("#selling").val());
var total = a*b;
$("#total").append(total)
.show('slow')
.css({"background":"yellow","font-size":50})
;
return false;
});
});
</script>
You can do several things:
total = total.toFixed([number of decimals]);
total = Math.round(total);
total = parseInt(total);
toFixed() will round your number to the number of decimals indicated.
Math.round() will round numbers to the nearest integer.
parseInt() will take a string and attempt to parse an integer from it without rounding. parseInt() is a little trickier though, in that it will parse the first characters in a string that are numbers until they are not, meaning parseInt('123g32ksj') will return 123, whereas parseInt('sdjgg123') will return NaN.
For the sake of completeness, parseInt() accepts a second parameter which can be used to express the base you're trying to extract with, meaning that, for instance,
parseInt('A', 16) === 10 if you were trying to parse a hexidecimal.
See Math.round(...).
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/round
In addition to the other answers about rounding, you are appending the answer to "total" by using
$("#total").append(total)
You need to replace the previous text rather than appending by using
$("#total").html(total)