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

Add a prefix to a calculated output (currency)

我有以下简单的计算,它将两个值相加。这些值与使用 "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>