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

时间:2018-08-06 08:50:19

标签: javascript html prefix calc

我有以下简单的计算,将两个值加在一起。这些值与兰特(南非货币)有关,该兰特以“ 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

4 个答案:

答案 0 :(得分:1)

是的,您只需将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>

答案 1 :(得分:0)

您可以使用正则表达式提取该文本,而不必显式添加文本。这样,您可以动态添加它:

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>

答案 2 :(得分:0)

您可以使用原生Intl.NumberFormat https://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);

答案 3 :(得分:0)

只需在输出之前附加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>