Variable Visions

Javascript Math Part 1

Published Fri. Mar. 15, 2013

Using Math.round, document.write, and a reg-ex function using .replace, .charAt, and .lastIndexOf to delimit and replace commas

<script type="text/javascript">

var gallonformula = 7.48;
var footandahalfmultiplier = 1.50;

function delimitNumbers(str) {
      return (str + "").replace(/\b(\d+)((\.\d+)*)\b/g, function(a, b, c) {
          return (b.charAt(0) > 0 && !(c || ".").lastIndexOf(".") ? b.replace(/(\d)(?=(\d{3})+$)/g, "$1,") : b) + c;
      });
}



document.write('<div class="galloncontainer mobile">');
document.write('2\' X 2\' X 12\" = ' + '<strong>' + delimitNumbers(Math.round(2 * 2 * gallonformula) + ' gallons' + ' &raquo;</strong><br />'));
document.write('2\' X 2\' X 18\" = ' + '<strong>' + delimitNumbers(Math.round(2 * 2 * gallonformula * + footandahalfmultiplier) + ' gallons' + ' &raquo;</strong><br />'));
document.write('</div>');
document.write('<div class="galloncontainer mobile">');
document.write('3\' X 5\' X 12\" = ' + '<strong>' + delimitNumbers(Math.round(3 * 5 * gallonformula) + ' gallons' + '</strong><br />'));
document.write('3\' X 5\' X 18\" = ' + '<strong>' + delimitNumbers(Math.round(3 * 5 * gallonformula * + footandahalfmultiplier) + ' gallons' + '</strong><br />'));
document.write('</div>');


</script>








.galloncontainer {
        float:left;
        width: 31%;
        margin: 0px 2px 2px 0px;
        padding: 4px;
        color: #333;
        font-family:sans-serif;
        font-size:10px;
    }
    .galloncontainer:hover {
        background: #FFF !important;
    }
    .galloncontainer:nth-child(even) {
        background: #ebe8e8;
    }
    .galloncontainer.even {
        background: #ebe8e8;
    }
    .galloncontainer:nth-child(odd) {
        background: #e4e2e2;
    }   
    .galloncontainer.odd {
        background: #e4e2e2;
    }
    .clear {
        clear:both !important;       
    }   
    @media (max-width: 959px) {
        .galloncontainer.mobile {
            width: 46% !important;
        }
    }
    @media (max-width: 767px) {
        .galloncontainer.mobile {
        }
    }
    @media (max-width: 321px) {
        .galloncontainer.mobile {
            float:none !important;
            width: 100% !important;
        }
    }

Keywords:Javascript Math.round, document.write, reg-ex function, .replace, .charAt, and .lastIndexOf to delimit and replace commas