javascript - 将小数值与空格字符串对齐?

标签 javascript alignment decimal padding

我在添加空格以对齐小数位时遇到问题。我理解其中的逻辑,但我无法将其转化为代码。

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 的新数组中。这就是它目前的样子。

当前布局:

Current layout

我将如何进行循环以检查不同长度的货币值需要多少个空格?

最佳答案

为什么不做这样的事情呢? (一些带有实际文本/数字的示例)

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/

相关文章:

javascript - Google Charts API 数据表单元格颜色

javascript - HTML SELECT 元素使用哪种算法在您键入时显示结果?

python - numpy.loadtxt "could not convert string to float"

c - 如何在C中将非常大的二进制转换为十进制

c++ - 我如何在不知道 float 长度的情况下进行 fscanf?

java - 将数字的十六进制表示形式转换为十进制值的有效方法

javascript - React Native - 将函数的返回值设置为组件的属性不起作用

javascript - 为什么在文本框中按 Enter 键会单击第一个按钮并提交表单

css - 如何在 CSS 中将文本居中对齐并右对齐?

jquery - jqGrid行垂直对齐不居中