Search code examples
javascriptcropdigits

Javascript separation and cropping and round digits


I have a problem with this short script. Script must show digits like this 10 987.23 or 10 987 (2 symbols after dot or not), but showing NaN. What am I doing wrong?

<script>
var dohzavershen = "10 987.23456457457"; // corrected
dohzavershen = dohzavershen.replace(/.+?(?=\D|$)/, 
  function(f) {
    return f.replace(/(\d)(?=(?:\d\d\d)+$)/g, "$1 ")
  ;}
);

document.write(Number(dohzavershen).toFixed(0));

<script>

Solution

  • var dohzavershen = "10 987.23456457457"; // corrected
    
    function formatter(n, k) {
       var split = n.split('.');
       if (split.length > 1) {
          split[split.length-1] = split[split.length-1].substring(0, k);
       }
       return k > 0 ? split.join('.') : split[0];
    }
    
    formatter(dohzavershen, 2)
    

    Something like this might work. But note that this does not round off the number but just selects the first two digits after the decimal point. The k>0 is just to make sure you dont get a "1234.", you can handle it any which way you think is appropriate