简体   繁体   中英

From string to integer Javascript

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM