nyk0r

format float

Sep 28th, 2012
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 1.31 KB | None | 0 0
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5.     <style type="text/css">
  6.        body {
  7.           font-weight:bold;
  8.           font-size:24px;
  9.        }
  10.     </style>
  11. </head>
  12.  
  13. <body>
  14. </body>
  15.  
  16. <script type="text/javascript">
  17.     function formatFloat(num) {
  18.        var frac = ((num - Math.floor(num)) * 1000), part, result = '';
  19.        num = Math.floor(num);
  20.        
  21.        while (num >= 1000) // integer part
  22.        {
  23.            part = (num - Math.floor(num/1000)*1000).toString(); // part = three less significant digits
  24.            num = Math.floor(num/1000);
  25.            while (part.length < 3) // 123.023.123  if sepMilhar = '.'
  26.                part = '0' + part;    
  27.           result = part + result;
  28.           if (num > 0)
  29.                result = ',' + result;
  30.        }
  31.        if (num > 0)
  32.          result = num.toString() + result;
  33.        
  34.        
  35.        if (frac != 0)
  36.          result += '.' + frac.toFixed();
  37.        
  38.        return result;
  39.     }
  40.    
  41.     document.body.innerHTML =
  42.        '<ul>' +
  43.          '<li>' + formatFloat(100500) + '</li>' +
  44.          '<li>' + formatFloat(50.23) + '</li>' +
  45.          '<li>' + formatFloat(1010107) + '</li>' +
  46.          '<li>' + formatFloat(1010107.25) + '</li>' +
  47.       '</ul>';
  48.  </script>
Advertisement
Add Comment
Please, Sign In to add comment