基于最大后继零在逗号后删除零 [英] Removing zeros after comma based on maximum consequent zeros
问题描述
我有一个带有网格的页面,其中保存了用户号码.它具有以下模式-每个数字以逗号后的3位数字结尾.看起来不太好,例如当用户的输入是
I have a page with a grid where user's numbers get saved. It has a following pattern - every number ends with 3 digits after comma. It doesn't look nice, when for example user's input is
123,450
123,670
123,890
最好在逗号后再加上2个数字,因为最后一个0
绝对毫无意义且多余.
It's much better to have just 2 numbers after comma, because last 0
is absolutely meaningless and redundant.
仅当数组中的至少一个元素不以0
The way it still should have 3 digits is only if at least one element in an array doesn't end up with 0
例如:
123,455
123,450
123,560
在这种情况下,数组的第一个元素的最后一位不等于0
,因此所有元素都应具有3位.带有2个或1个零的相同故事
In this case 1st element of the array has the last digit not equal to 0
and hence all the elements should have 3 digits. The same story with 2 or 1 zeros
零是多余的:
123,30
123,40
123,50
零是必要的
123,35
123,40
123,50
问题是如何以编程方式实现它?我是这样开始的:
The question is how can I implement it programatically? I've started like this:
var zeros2Remove = 0;
numInArray.forEach(function(item, index, numInArray)
{
var threeDigitsAfterComma = item.substring(item.indexOf(',') + 1);
for(var j = 2; j <= 0; j--)
{
if(threeDigitsAfterComma[j] == 0)
{
zeros2Remove =+ 1;
}
else //have no idea what to do..
}
})
在我的实现中,我不知道该怎么做,因为我必须遍历每个元素,但是如果至少一个数字的最后一位等于零,则将其中断.外循环,但不知道如何,而且我绝对确定我不必...
Well in my implementation I don't know how to do it since I have to iterate through every element but break it if at least 1 number has a last digit equal to zero.. In order to do that I have to break outer loop, but don't know how and I'm absolutely sure that I don't have to...
推荐答案
我认为以下代码正是您要寻找的代码,请操纵数字并查看更改:
I think the following code what you are looking for exactly , please manipulate numbers and see the changes :
var arr = ["111.3030", "2232.0022", "3.001000", "4","558.0200","55.00003000000"];
var map = arr.map(function(a) {
if (a % 1 === 0) {
var res = "1";
} else {
var lastNumman = a.toString().split('').pop();
if (lastNumman == 0) {
var m = parseFloat(a);
var res = (m + "").split(".")[1].length;
} else {
var m = a.split(".")[1].length;
var res = m;
}
}
return res;
})
var maxNum = map.reduce(function(a, b) {
return Math.max(a, b);
});
arr.forEach(function(el) {
console.log(Number.parseFloat(el).toFixed(maxNum));
});
这篇关于基于最大后继零在逗号后删除零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!