我在添加空格以对齐小数位时遇到问题。我理解其中的逻辑,但我无法将其转化为代码。
for(var j in totals_array)
{
var amount = format_numeric_with_commas(totals_array[j].amount);
var currency = totals_array[j].currency;
if(j < 1)
{
costs_total.push(currency + " " + amount + "\x0A");
}
else
costs_total.push(currency + Array(0).join(" ") + amount + "\x0A");
}
totals_array
包含许多对象,如下所示。
{"currency":"AUD","amount":210543}
format_numeric_with_commas
以适当的格式给我存储在变量 amount
中的金额值。 currency
获取值的货币,即 GBP、USD 等。if 语句用于检查它是否是数组中的第一个索引。因为我已经对顶部最高的值进行了排序。所以我想要的是让其他值与最高数字的小数点对齐。
我将货币类型和值(value)放入一个名为 costs_total
的新数组中。这就是它目前的样子。
当前布局:
我将如何进行循环以检查不同长度的货币值需要多少个空格?
最佳答案
为什么不做这样的事情呢? (一些带有实际文本/数字的示例)
costs_total.push(String.Format("{0} {1,12:N}\x0A", "USD", 123456.0));
// "USD 123,456.00\n"
costs_total.push(String.Format("{0} {1,12:N}\x0A", "AUD", 123.0));
// "AUD 123.00\n"
costs_total.push(String.Format("{0} {1,12:N}\x0A", currency, amount));
您只需要找到最大数字的位数并适本地设置宽度(在本例中为 12)。
关于javascript - 将小数值与空格字符串对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39838104/