Search code examples
javascripthtmlprefixcalc

Add a prefix to a calculated output (currency)


I have the following simple calculation which adds two values together. These values relate to the Rand (South African currency) which is identified using an "R" as a prefix).

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>

Is it possible for the output value to include "R" as a permanent prefix? For example, 4 + 4 = R8


Solution

  • Yes sure you've just to Add the R prefix to the output result, like :

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

    Working snippet :

    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>