简体   繁体   English

在javascript中将十进制数转换为百分比

[英]Convert a decimal number to percentage in javascript

I did a code to return a json, example bellow:我做了一个返回json的代码,示例如下:

[
  {
    "id": "12345",
    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",
    "title": "Training Summary Report",
    "description": "",
    "link": "",
    "labels": [
      {
        "filter": "type",
        "value": "course 1"
      },
      {
        "filter": "Subject",
        "value": "Sub. 1239"
      },
      {
        "filter": "Idea",
        "value": "Idea . 53"
      }
    ]
  }

    {
    "id": "12345",
    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",
    "title": "Training Summary Report",
    "description": "",
    "link": "",
    "labels": [
      {
        "filter": "type",
        "value": "course 1"
      },
      {
        "filter": "Subject",
        "value": "Sub. 1239"
      },
      {
        "filter": "Idea",
        "value": "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245"
      }
    ]
  }
]

These json what I have as result.这些json是我的结果。 I would like to change the decimal numbers in Idea value to percentage:我想将 Idea 值中的十进制数字更改为百分比:

53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245

Expect result:

53-34-98:0,45%, 98-11-00:9.8%, 44-22-88:9.875%, 22-98-90:32%

So the result become:所以结果变成了:

{
    "id": "12345",
    "header": "<a class=\"card-link\" href=\"http://www.google.com\" target=\"_blank\"> 12345</a>- solved-1",
    "title": "Training Summary Report",
    "description": "",
    "link": "",
    "labels": [
      {
        "filter": "type",
        "value": "course 1"
      },
      {
        "filter": "Subject",
        "value": "Sub. 1239"
      },
      {
        "filter": "Idea",
        "value": "Idea . 53-34-98:0,45%, 98-11-00:9.8%, 44-22-88:9.875%, 22-98-90:32%"
      }
    ]
  }

My code is the following:我的代码如下:

result = ""
            if(queryResult.final_Matrix[index] == null){
                if(queryResult.idea[index] != null){
                    result = "Idea. " + queryResult.idea[index]
                }
            }
            else{
                result = "Idea. " + queryResult.final_Matrix[index]  // the result of this line is: "value": "Idea . 53-34-98:0,45%, 98-11-00:9.8%, 44-22-88:9.875%, 22-98-90:32%"
            }

Example final_Matrix column dataset:示例 final_Matrix 列数据集:

53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245

Someone can help me please to change my code to convert the decimal number to percentage ?有人可以帮我更改我的代码以将十进制数转换为百分比吗? Thank you谢谢

You can first split the string containing your datas ( queryResult.final_Matrix[index] ) to get each parts separatly, then, for each parts, split again using ":" and apply some math (multiply by 100) to get the percentage :您可以首先拆分包含数据的字符串( queryResult.final_Matrix[index] )以分别获取每个部分,然后,对于每个部分,使用":"再次拆分并应用一些数学运算(乘以 100)以获得百分比:

 let input = "53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245"; let times = input.split(", "); const result = []; times.forEach((elem) => { const tempArr = elem.split(":"); result.push(tempArr[0] + ":" + (Math.round((tempArr[1] * 100) * 100) / 100) + "%"); }); let finalResult = result.join(", "); console.log(finalResult);

You can loop, split according to the strings, reducing the array of tokens (those separated by comma , ) and finally rebuild the tokens with the transformed percentage values.您可以循环,根据字符串拆分,减少标记数组(由逗号,分隔的标记),最后使用转换后的百分比值重建标记。

 let arr = [ { "id": "12345", "header": "<a class=\\"card-link\\" href=\\"http://www.google.com\\" target=\\"_blank\\"> 12345</a>- solved-1", "title": "Training Summary Report", "description": "", "link": "", "labels": [ { "filter": "type", "value": "course 1" }, { "filter": "Subject", "value": "Sub. 1239" }, { "filter": "Idea", "value": "Idea . 53" } ] }, { "id": "12345", "header": "<a class=\\"card-link\\" href=\\"http://www.google.com\\" target=\\"_blank\\"> 12345</a>- solved-1", "title": "Training Summary Report", "description": "", "link": "", "labels": [ { "filter": "type", "value": "course 1" }, { "filter": "Subject", "value": "Sub. 1239" }, { "filter": "Idea", "value": "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245" } ] }]; arr.forEach(({labels}) => { labels.forEach(label => { let [_, value] = label.value.split("Idea . "); if (value) { label.value = "Idea . " + value.split(",").reduce((a, t) => { let [str, perc] = t.split(":"); if (perc) str += ":" + (Number(perc.trim()) * 100).toFixed(2) + "%" return a.concat(str); }, []).join(); } }); }); console.log(arr);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Here is the object conversion using string split , join methods.这是使用字符串splitjoin方法的对象转换。

 const convert = item => { const labels = item.labels.map(label => { if (label.value.includes("Idea")) { return { ...label, value: label.value .split(",") .map(val => { const strs = val.split(":"); const last = strs.pop(); strs.push(`${Math.round(Number(last) * 100 * 100) / 100}%`); return strs.join(":"); }) .join(",") }; } else { return { ...label }; } }); return { ...item, labels }; }; const arr = [ { id: "12345", header: '<a class="card-link" href="http://www.google.com" target="_blank"> 12345</a>- solved-1', title: "Training Summary Report", description: "", link: "", labels: [ { filter: "type", value: "course 1" }, { filter: "Subject", value: "Sub. 1239" }, { filter: "Idea", value: "Idea . 53" } ] }, { id: "12345", header: '<a class="card-link" href="http://www.google.com" target="_blank"> 12345</a>- solved-1', title: "Training Summary Report", description: "", link: "", labels: [ { filter: "type", value: "course 1" }, { filter: "Subject", value: "Sub. 1239" }, { filter: "Idea", value: "Idea . 53-34-98:0.0045, 98-11-00:0.09856, 44-22-88:0.09875, 22-98-90:0.3245" } ] } ]; console.log(arr.map(convert));

1) loop to your raw data 1)循环到您的原始数据
2) on the key 'label', search the array with 'filter'==='Idea' 2) 在键 'label' 上,使用 'filter'==='Idea' 搜索数组
3) perform split and join to convert 3)执行split和join转换

data=[{...'label':{'filter':'Idea'...}...},{}];

var labels=[],valueInd=[],value=[],div2=[];
data.map((element)=>{
  labels = element.labels;
  valueInd=labels.findIndex(elem=>elem.filter==='Idea');
  value=labels[valueInd].value;
  value=value.split(' . ')[0]+ ' . '+value.split(' . ')[1].split(',').map((elem)=>{
          var div2=elem.split(':');
         return div2.length>1?div2[0]+':'+(Number(div2[1])*100).toFixed(2)+'%':div2[0];
  }).join(',');
  labels[valueInd].value=value;
});

console.log(data);

Demo演示

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

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