为计算的输出(货币)添加前缀



我有下面的简单计算,它将两个值相加。这些值与兰特(南非货币(有关,兰特使用"R"作为前缀进行识别(。

function calculate() {
var A = parseFloat(document.getElementById("A").value);
var B = parseFloat(document.getElementById("B").value);
var total = A+B;

document.getElementById("total").value = total;
};
<input type="text" id="A" placeholder="First amount in R"> +
<input type="text" id="B" placeholder="Second amount in R">
<input type="button" onClick="calculate()" value="Calculate"> = 
<output id="total">R</output>

输出值是否可能包含"R"作为永久前缀?例如,4+4=R8

是的,你只需要在输出结果中添加R前缀,比如:

document.getElementById("total").value = 'R' + total;

工作片段:

function calculate() {
var A = parseFloat(document.getElementById("A").value);
var B = parseFloat(document.getElementById("B").value);
var total = A + B;
document.getElementById("total").value = 'R' + total;
};
<input type="text" id="A" placeholder="First amount in R"> +
<input type="text" id="B" placeholder="Second amount in R">
<input type="button" onClick="calculate()" value="Calculate"> =
<output id="total">R</output>

您可以使用正则表达式提取该文本,而不是显式添加它。通过这种方式,您可以动态添加:

function calculate() {
let el = document.getElementById("total");
let txt = el.value.match(/(w)/)[0]; // extract the text 'R'
var A = parseFloat(document.getElementById("A").value);
var B = parseFloat(document.getElementById("B").value);
var total = A + B;
el.value = txt + total;
};
<input type="text" id="A" placeholder="First amount in R"> +
<input type="text" id="B" placeholder="Second amount in R">
<input type="button" onClick="calculate()" value="Calculate"> =
<output id="total">R</output>

您可以使用本机Intl.NumberFormathttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat

var total = new Intl.NumberFormat('af-NA',
{ style: 'currency', currency: 'ZAR' }).format(A + B);

只需在输出前附加string R,如下所示:

function calculate() {
var A = parseFloat(document.getElementById("A").value);
var B = parseFloat(document.getElementById("B").value);
var total = A+B;

document.getElementById("total").value = `R${total}`;
};
<input type="text" id="A" placeholder="First amount in R"> +
<input type="text" id="B" placeholder="Second amount in R">
<input type="button" onClick="calculate()" value="Calculate"> = 
<b><output id="total">R</output></b>

最新更新