简体   繁体   English

javascript在数组中循环并分配toFixed(2)

[英]javascript loop through the array and assign the toFixed(2)

i have a javascript array named as array and when i console.log(array); 我有一个名为array的JavaScript数组,当我console.log(array); i get 我得到

console 安慰

Array[6], Array[6], Array[6], Array[6]

and the each array has values 每个数组都有值

0: Array[6]
1: Array[6]
2: Array[6]
3: Array[6]

and each array has 每个数组都有

    0: Array[6]
    0: "Jan"
    1: 5672.4000001
    2: "$5672.4000001"
    3: "<div class='tooltip'>↵ <p><b>Time Period:</b> Jan</p>↵ <p><b>Cost:</b> $5672.4000001</p>↵ <p><b>Data Used:</b> 277 GB</p>↵ </div>"
    4: "color: rgb(66, 133, 244)"
    5: 283626
1: Array[6]
0: "Feb"
1: 4673.62
2: "$4673.62"
3: "<div class='tooltip'>↵ <p><b>Time Period:</b> Feb</p>↵ <p><b>Cost:</b> $4673.62</p>↵ <p><b>Data Used:</b> 228 GB</p>↵ </div>"
4: "color: rgb(66, 133, 244)"
5: 233681

and further values are given 并给出进一步的值

now what i want is to fetch the [2] index of each array in the first array it is "$5672.4000001" and convert it into the proper format like "$5672.40" upto two decimal places 现在我想要的是获取第一个数组中每个数组的[2]索引,它是“ $ 5672.4000001”并将其转换为正确的格式,例如“ $ 5672.40”,最多两位小数

i can loop through each index as 我可以遍历每个索引为

array.forEach(function(data) {

  });

but i dont know how to assign the rounding of to two decimal places for each array's data[2] 但是我不知道如何为每个数组的数据分配舍入到小数点后两位[2]

any help would be appreciated 任何帮助,将不胜感激

You can use indexOf to find where the decimal is placed. 您可以使用indexOf查找小数所在的位置。 Like this: 像这样:

var str = array[2];
var theDot = str.indexOf(".");
var formatedPrice = str.substr(0, theDot+3);

formatedPrice will allways contain two decimals, like this "$5672.40" formatedPrice将始终包含两个小数,例如"$5672.40"
(Unless you have more than one decimal, in that case you need to find the last dot). (除非您有多个小数,否则,您需要找到最后一个点)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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