1
    <form>
    <label>Value:</label>
    <input name="value" id="value" value="" placeholder="250000" type="number">
    <br><br>
    <label>Growth:</label>
    <select name="growth" id="growth">
        <option value=".05" selected="selected">0-5%</option>
        <option value=".08">5-10%</option>
        <option value=".10">10-20%</option>
        <option value=".12">20+%</option>
    </select>
    </form>
    <p id="total"></p>

$("#value,#growth").change(function () {
    var number= $('#value').val();
    var goal= $('#growth').val()*1;
    if ( number >= 1 && number <=250000 ) {
        var growth = goal + .02;
    } 
    if ( number >= 250000 && number <=500000 ) {
        var growth = goal + .01;
    } 
    if ( number >= 500000 && number <=500000000 ) {
        var growth = goal;
    }
    var total = number*growth;
    $("#total").text(total);
});

I need to create a simple calculator that based on different variables entered will multiply a percentage by a value from another field and give a dollar figure amount. I have everything working exactly as desired. However, I want the final "Total" number to be converted to a whole number and commas in the appropriate place.

Example: If 100,000 is entered as the value and 0-5% is selected as the growth the total is outputting at 7000.00000001. I would like this number to be formatted as 7,000. I have looked at other questions and not found an appropriate response to what I am trying to achieve. I did try to use the chosen answer here: Add comma to numbers every three digits

However, it does not round to a whole number (or at least 2 decimals) and it continues to add commas after the decimal point. This is included in the fiddle below. Is there a simple way to achieve what I'm trying to do? Thanks

Here is a link to my fiddle: https://jsfiddle.net/xpvt214o/522647/

cameron
  • 420
  • 5
  • 17

1 Answers1

3

I added a regex function and used JavaScript Math.Round function.

Below is a working example tested in your jsfiddle:

$.fn.digits = function(){ 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}

$("#value,#growth").change(function () {

    var number= $('#value').val();
    var goal= $('#growth').val()*1;
    if ( number >= 1 && number <=250000 ) {
        var growth = goal + .02;
    } 
    if ( number >= 250000 && number <=500000 ) {
        var growth = goal + .01;
    } 
    if ( number >= 500000 && number <=500000000 ) {
        var growth = goal;
    }
    var total = number*growth;
    total = Math.round(total);
    //total = Number(total).toFixed(2);
    $("#total").text(total);
    $("#total").digits();
});

You want to keep the decimals instead of a whole number use ('#total).toFixed(2); instead of round. just commit out the round() line and uncommit the tofixed() line.

RegEX was provided from this answer Add comma to numbers every three digits

thatguy
  • 1,249
  • 9
  • 26