function FinalAmount() {
var FinalPrice = document.getElementById("FinalPrice");
let AllProductTotalPrice = 0;
for (let index = 0; index < OrderedProductList.length; ++index) {
alert;
var CurrentProductTotal = 0;
CurrentProductTotal = OrderedProductList[index].TotalPrice;
console.log(CurrentProductTotal);
AllProductTotalPrice += CurrentProductTotal;
console.log(AllProductTotalPrice);
}
FinalAllProductPrice = AllProductTotalPrice;
FinalPrice.innerText = "RM" + FinalAllProductPrice;
}
This is my javascript code. I would have a question about why the console.log(CurrentProductTotal) is already an integer but the above AllProductTotalPrice is a string value. Is there any way to let its sum as an integer and bring it to the below FinalAllProductPrice. Please help me TT
I think the easiest way would be to
use Number() to parse a string to a number. (we don't define integers specifically in javascript)
const num = "1234"
Number(num)
⚠️ If you give it a string which does not solely consist out of numbers it will return NaN
So in your example that would be:
CurrentProductTotal = OrderedProductList[index].TotalPrice
Now to your questions:
console.log() automatically displays it formatted for you. I would use the typeof operator to check whether CurrentProductTotal is really a number, or a string which the console formats differently which is a bit confusing.
Try this in your browser console:
const num = "1234"
> undefined
num
> '1234'
console.log(num)
> 1234 // formatted like a number
console.log(num, typeof num)
> 1234 string // still formatted like a number, but a string in reality
Related
I tried several methods (Number, parseFloat, *1) of string to number conversion but everytime I can't get desired value:
var str = ["0.20", "day"];
var num;
str.forEach(v => {
num = parseFloat(v);
console.log(num);
})
How can I get 0.2 as a number and "day" as a string [0.2, "day"] in the result?
Check if the parsed value is not a number (NaN). If so, print the string as it is, otherwise convert it.
l = parseFloat(v) Here I try to convert the value to float and assign the result to the variable l
isNaN() Is the built in method that checks if a certain result is not a number and is what I use to check if variable l is a number or not.
? is a ternary operator
v is printed if it is not a number (if it is NaN)
Otherwise l (which is the parsed value) is printed
var str = ["0.20", "day"];
console.log(
str.map(v => isNaN(l = parseFloat(v))? v : l)
)
/* A shorter way is to do */
console.log(
str.map(v=>+v||v)
)
Why doesn't this block work? I Used isNaN() and that works but not this, why? Javascript is behaving weirdly.
if( (typeof parseInt(returnedArr[count]) == 'number')
{
totalWorth= parseInt(totalWorth)+ parseInt(returnedArr[count]);
//document.write(returnedArr[count]);
}
Code:
function addWorth()
{
var table1= document.getElementById("tableNetWorths");
var rowCount1= table1.rows.length;
//var row1= table1.insertRow(rowCount1);
var arr= [];
for(var count = 0; count < rowCount1; count++)
{
arr.push(table1.rows[count].cells[1].innerHTML);
}
arr.shift();
return arr;
}
function showWorthSum()
{
var returnedArr= addWorth();
//returnedArr.push(addWorth());
totalWorth= 0;
var arrCount= returnedArr.length;
for(var count = 0; count < arrCount; count++)
{
if( (typeof parseInt(returnedArr[count]) == 'number')
{
totalWorth= parseInt(totalWorth)+ parseInt(returnedArr[count]);
//document.write(returnedArr[count]);
}
}
return parseInt(totalWorth);
}
If I use isNaN then that works but not this, why? My array looks like this:
{"100", "200", "asdasdadsa", "1"}
Because typeof NaN is "number":
console.log(typeof NaN);
NaN is a special value* of the number type, not its own type.
You haven't shown your code that uses isNaN, but note that if you pass a string into isNaN, it will be implicitly converted to number before being tested to see if the result of doing that is NaN (as though you had called Number(x) on it, or applied unary + or any of the non-addition math ops [-, *, /, etc.]).
Separately:
Beware that parseInt will happily parse a string that only starts with a number, ignoring the part after it that isn't numeric. For instance, parseInt("123abc") is 123.
Beware that when used without its second argument, parseInt will infer the number base (radix) from the string, so parseInt("0x10") is 16.
When dealing with user input, handling both of those situations intentionally is usually best:
function parseIntStrict(str) {
str = str.trim();
if (!/^\d+$/.test(str)) {
return NaN;
}
return parseInt(str, 10);
}
(Note that doesn't attempt to support scientific notation input; users don't usually input it.)
And for floating point:
function parseFloatStrict(str) {
str = str.trim();
if (!str) {
return NaN;
}
return +str;
}
(That does support scientific notation, but only as a byproduct of only checking for blank strings before handing off to built-in numeric conversion.)
Applying that to your code:
// I assume totalWorth is already a number
var entry = parseIntStrict(returnedArr[count]);
if (!isNaN(entry)) {
totalWorth = totalWorth + entry;
}
* Technically, per the IEEE-754 standard JavaScript uses, NaN is any of a range of values that all mean "not a number."
This is because the values in the array that you consider to be numbers are actually strings. For example, 100 is a number, but '100' is a string. typeof 123 will return 'number', but typeof '123' will return 'string'.
This means that all the values in your array are of type string and your code will not enter the if statement, if you use that approach.
However, since isNaN checks if an element in not a number, your code will work with that.
I am wondering why the following works:
oldversion = "1.3.52";
newversion = "1.3.54";
if (newversion > oldversion) {
console.log('test');
}
but this does not:
if (1.3.54 > 1.3.52) {
console.log('test');
}
I know that the last example won't work because they are not actual numbers. But I am trying to find out what JavaScript is doing when it encounters a string with a number in it.
This is what I found on W3Schools' JavaScript Comparison and Logical Operators page:
When comparing a string with a number, JavaScript will convert the
string to a number when doing the comparison.
So how come it converts the string to a number and suddenly I am not getting an Uncaught SyntaxError: Unexpected number anymore?
You could use a function which iterates the segments.
function checkVersion(a, b) {
var aa = a.split('.').map(Number),
bb = b.split('.').map(Number),
i,
r = 0,
l = Math.max(aa.length, bb.length);
for (i = 0; !r && i < l; i++) {
r = (aa[i] || 0) - (bb[i] || 0);
}
return r;
}
var oldversion = "1.3.52",
newversion = "1.3.54";
if (checkVersion(newversion, oldversion) > 0) {
console.log('test');
}
As mentioned in the comments, it's actually doing a string compare and not trying to turn anything into numbers.
You can verify this by trying:
var a = "a";
var b = "b";
console.log(a>b) // gives false
var a = "a";
var b = "b";
console.log(b>a) // gives true
As you say, when you compare a number and a string, the string gets transformed into a number. However, if the string contains an invalid number, the result will be NaN. This is funny due to the fact that:
NaN > 15 === false
NaN < 15 === false
So:
"1.3.52" > 1.4 === false
"1.3.52" < 1.4 === false
Obviously (and as you said in your post), comparing 1.3.52 with 1.3.54 will throw an exception because they're not valid numbers.
Why "1.3.52" is interpreted bigger than '1.12.10'?
Strings are compared using Unicode code point order. For example, "Banana" comes before "cherry". "9" is bigger than "80", but because "80" comes before "9" in Unicode order. Thus, "1.3.52" is interpreted as bigger than '1.12.10'.
An easy way to find out order between strings and not getting tricked is using sort. For instance, ["1.3.52", "1.12.10", "1.11.0.0.0"].sort()
#Nina's solution should be the accepted answer, as it will be easier to understand I think. But anyway..
function versionGreaterEqual(newversion, oldversion) {
var ov = oldversion.split('.').map(Number), //credit Nina :)
nv = newversion.split('.').map(Number);
return nv.reduce(function (a,b,i){
return a+=b>=ov[i];
},0)===nv.length;
}
console.log(versionGreaterEqual("1.3.54", "1.3.52")); //true
console.log(versionGreaterEqual("1.3.54", "1.13.52")); //false
i would like to format decimal values to specific format as like
1.23 should be shown as 0001.23 using javascript. is there any specific functions like toPrecision(), tofixed() in javascript to handle these kind of formatting or any pointers to go ahead with any solutions?
here preceeding decimal is dynamic one.
for example :
i have 2 values :
first value : 99.4545
second value : 100.32
in this second value has higher length (3)before decimal and first value has higher length after decimal(4). so subtracted result(0.8655) of this should be formatted as ###.#### (000.8685)
thank you
Just make a function that does what you want it to. Here is an example you can expand on if you want.
function pad(num, padSize){
var numString = "" + num.split('.')[0];
if(num.length < padSize){
var numZeroes = padSize-num.length;
var zeroes = "";
while(numZeroes){zeroes += "0"; numZeroes--;}
return zeroes + num;
}else return num;
}
if you want to lpad some 0 onto 1.23 you can do the following
var value = 1.23
value = ("0000000"+ value).slice(-7);
Change the -7 to be whatever you want the total string length including the decimal point to be.
Added after question edit
The above should handle your question pre-edit but for the rest of it you'll need something like this.
var formatNum = function (num, preLen, postLen) {
var value = num.split("."),
padstring = "0";
padLen = (preLen > postLen)?preLen:postLen;
for (i = 0; i < padLen; i++) {
padstring += padstring;
}
if (typeof(value[1]) === "undefined") {
value[1] = "0";
}
return ((padstring + value[0]).slice(-preLen)+ "." + (value[1] + padstring).substring(0,postLen));
}
This takes the number you want formatted and the lengths you want each string to be on either side of the '.'. It also handles the case of an integer.
If you want it to output any other cases such as returning an integer, you'll have to add that in.
Try to use a string, like "000" + some value
I have scenario where if user enters for example 000.03, I want to show the user it as .03 instead of 000.03. How can I do this with Javascript?
You can use a regular expression:
"000.03".replace(/^0+\./, ".");
Adjust it to your liking.
This actually is trickier than it first seems. Removing leading zero's is not something that is standard Javascript. I found this elegant solution online and edited it a bit.
function removeLeadingZeros(strNumber)
{
while (strNumber.substr(0,1) == '0' && strNumber.length>1)
{
strNumber = strNumber.substr(1);
}
return strNumber;
}
userInput = "000.03";
alert(removeLeadingZeros(userInput));
How about:
function showRounded(val) {
var zero = parseInt(val.split('.')[0],10) === 0;
return zero ? val.substring(val.indexOf('.')) : val.replace(/^0+/,'') );
}
console.log(showRounded('000.03')); //=> ".03"
console.log(showRounded('900.03')); //=> "900.03"
console.log(showRounded('009.03')); //=> "9.03"
Or adjust Álvaro G. Vicario's solution to get rid of leading zero's into:
String(parseFloat("090.03")).replace(/^0+\./, ".")
This function will take any string and try to parse it as a number, then format it the way you described:
function makePretty(userInput) {
var num,
str;
num = parseFloat(userInput); // e.g. 0.03
str = userInput.toString();
if (!isNaN(num) && str.substring(0, 1) === '0') {
str = str.substring(1); // e.g. .03
} else if (isNaN(num)) {
str = userInput; // it’s not a number, so just return the input
}
return str;
}
makePretty('000.03'); // '.03'
makePretty('020.03'); // '20.03'
It you feed it something it cannot parse as a number, it will just return it back.
Update: Oh, I see If the single leading zero needs to be removed as well. Updated the code.
Assuming your input's all the same format, and you want to display the .
user = "000.03";
user = user.substring(3);
You can convert a string into a number and back into a string to format it as "0.03":
var input = "000.03";
var output = (+input).toString(); // "0.03"
To get rid of any leading zeroes (e.g. ".03"), you can do:
var input = "000.03";
var output = input.substr(input.indexOf(".")); // ".03"
However, this improperly strips "20.30" to ".30". You can combine the first two methods to get around this:
var input = "000.03";
var output = Math.abs(+input) < 1 ?
input.substr(input.indexOf(".")) :
(+"000.03").toString();