Home  >  Article  >  Web Front-end  >  Detailed explanation on how to calculate the total price using JS

Detailed explanation on how to calculate the total price using JS

零下一度
零下一度Original
2017-06-23 09:56:151786browse

Yesterday, I connected the data and found that the total price of a product needs to be calculated. The quantity of the product is uncertain, the price of the product is uncertain, and the type of the product is uncertain. It is a bit confusing. After much thought, I did not expect to find a simple way to write it. Finally, I provide a simple way. Think about it.

First create two arrays for product quantity and product price;

let pro_num=[];

let pro_price=[];

and then create a new one An array contains the total price of a single product;

let pro_total_price=[];

After that, all the product quantities are obtained, the product price is put into the array, and the two arrays are looped;

  for(let i=0;i<pro_num.length;i++){
     for(let k=0;k<pro_price.length;k++){
         if(i==k){
            let alone_Total_price =parseFloat(pro_num[i])*parseFloat(pro_price[k]); //计算单个商品的总价
            pro_total_price.push(alone_Total_price); //获得所有的单个商品的总价
       }  
 }
   let sum=0;//初始化总价
   for(let i=0;i<pro_total_price.length;i++){
    sum+=pro_total_price[i] //单个总价相加   
 }
let total_price=sum.toFixed(2) //保留两位小数

If there are numerical changes or multiple total price calculations, clear the single total price array

pro_total_price.splice(pro_total_price.length,0);

The above is the detailed content of Detailed explanation on how to calculate the total price using JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn