0

I'm using an api to get some product details that display on my WordPress page (total beginner in WordPress & JavaScript).

  • Response from api: 1234
  • What i need: 12.34€
  • Sometimes i get no data back --> no price available

What i came up with so far:

    $(".offer-price, .-list-price").text(function(index, text) {
      if (text.length == 0) {
        return ""
      } else {
        var digits = text.split("");
        var back = digits.slice(-2).join("");
        var front = digits.slice(0,-2).join("");
        return front + "." + back + "\u20AC";
      }
    });

This function solves my problem. Since i am trying to improve / learn i would love to get some feedback from you guys on my approach and alternative ways to solve the issue. I'm sure there are better ways to tackle this?!

RandomDude
  • 1,101
  • 18
  • 33
  • I'm voting to close this question as off-topic because  This question belongs on another site in the Stack Exchange network http://codereview.stackexchange.com/ – zb' Mar 11 '17 at 17:48
  • 1
    Anyway it easer to do just by devision by 100 :) `Number(text)/100 + "\u20AC"` – zb' Mar 11 '17 at 17:50
  • Possible duplicate of [How can I format numbers as money in JavaScript?](http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript) – zurfyx Mar 11 '17 at 18:12

1 Answers1

1

you can Use regex

function format (num) {
return num
   .toFixed(2) // always two decimal digits
   .replace(".", ",") // replace decimal point character with ,
   .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.") + " €" // use . as a separator

}

from :https://blog.tompawlak.org/number-currency-formatting-javascript