问题描述
我正在使用以下代码:
Number(val).toLocaleString('pt-BR',{ style: 'currency',currency: 'BRL' });
在表格列上设置货币格式。它可以正常工作,但是货币符号未对齐,下图显示了我。
这就是我所希望的:
R$ 10,00
R$ 8,00
R$ 109,00
解决方法
有几种方法可以做到这一点,最终最好的方法将取决于您用来构建网格的组件。我在这里显示的是一种方法,主要是手动操作,因为问题中的信息很少。
我直接使用Intl.NumberFormat
,这就是toLocaleFormat
在幕后使用的方式。直接使用它的原因是获得formatToParts
,这是一个方便的函数,用于将数字格式化为一组零件。这样,我们就可以将货币符号与值分开。我在代码中包含了一个示例作为注释。
然后,只需将货币符号与值包装在单独的HTML元素中,然后使用CSS即可实现所需的对齐方式。将表格单元格的对齐方式设置为居中,但将符号的对齐方式设置为左,将值的对齐方式设置为右,并为符号和值设置宽度,即可完成工作。
请注意,您可能需要根据数据中实际获得的值来使用.amount
类的宽度。
var data = [10,8,109];
var table = document.querySelector('table');
var tbody = table.tBodies[0];
for (var i = 0; i < data.length; i++) {
var row = tbody.insertRow();
var cell = row.insertCell();
var datum = Number(data[i]);
var formatter = new Intl.NumberFormat('pt-BR',{
style: 'currency',currency: 'BRL'
});
var parts = formatter.formatToParts(datum);
/*
[
{
"type": "currency","value": "R$"
},{
"type": "literal","value": " "
},{
"type": "integer","value": "10"
},{
"type": "decimal","value": ","
},{
"type": "fraction","value": "00"
}
]
*/
var symbol = document.createElement('span');
symbol.className = "symbol";
// Get the "currency" part's value
symbol.textContent = parts.find(p => p.type === 'currency').value;
cell.appendChild(symbol);
var amount = document.createElement('span');
amount.className = "amount";
// Get all the parts after the "currency" and the "literal"
// Note that this may need to be adjusted depending on the locale and currency used!
// Another way of doing this would be to filter parts of type "integer","group",// "decimal",and "fraction" (or all types except "currency" and "literal") and join
// those.
amount.textContent = parts.slice(2).map(p => p.value).join('');
cell.appendChild(amount);
row.appendChild(cell);
tbody.appendChild(row);
}
td {
min-width: 200px;
text-align: center;
border: solid;
}
.symbol {
display: inline-block;
min-width: 20px;
text-align: left;
}
.amount {
display: inline-block;
min-width: 70px;
text-align: right;
}
<table>
<tbody>
</tbody>
</table>