How to change value in prize list with .toFixed(2) and change point to comma?

169 views Asked by At
<ul id="mylist">
    <li>my price:<span>29.95</span> &euro;</li>
</ul>

$( document ).ready(function() {
   $("#mylist li span").each( function() {
      $(this).text( Number($(this).text()) * 1.03 );
   });
});

I try to update a prize value by multiplying it with 1.03. The value should be rounded so that the result of this example is 30,85 . Could someone please help me?

1

There are 1 answers

0
Tyler Roper On BEST ANSWER

I'll break this down into three steps:

  1. Round our value to the hundredths place by using Math.round, multiplying our value by 100, and then dividing it by 100. This is a simple trick for proper place-rounding.
  2. Convert our rounded value to a string by appending "" to it.
  3. Use .replace(".",",") to change the point to a comma.

JSFiddle: https://jsfiddle.net/vLxj8bfs/2/

$( document ).ready(function() {
   $("#mylist li span").each( function() {
      var unrounded = Number($(this).text()) * 1.03;
      var rounded = Math.round(unrounded * 100) / 100;
      var strRounded = (rounded + "").replace(".", ",");
      $(this).text(strRounded);
   });
});

This could really be written in one line, but for explanation and readability, I've broken the values down a bit.