#1
  1. A Change of Season
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    3,167
    Rep Power
    220

    How to round these numbers?


    Hello. How can I round these?

    1.01 to 1.00
    1.05 to 1.00
    1.11 to 1.10
    1.15 to 1.10
    1.19 to 1.20

    I basically want to get rid of the second decimal value. 12.1X and turn that to zero!

    Currently, I do this but it's not exactly what I want. I lose the first decimal point as well and both first and second decimal values turns to .00
    Here is my code:

    Code:
    $('#total').val(format_currency(Math.round(total)));
    function format_currency(total) 
        	{
    		    var neg = false;
    		    if(total < 0) {
    		        neg = true;
    		        total = Math.abs(total);
    		    }
    		    return parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
    		}
    Thanks
    Last edited by English Breakfast Tea; April 4th, 2017 at 02:02 AM.
  2. #2
  3. Lazy Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,280
    Rep Power
    9645
    Getting rid of the second decimal would turn 1.19 into 1.1...

    How about just normal rounding rules: always round down, always round to zero, or always round to the nearest .1?
  4. #3
  5. A Change of Season
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    3,167
    Rep Power
    220
    "Getting rid of the second decimal" I meant rounding it to zero. How can I do that?

    "How about just normal rounding rules".

    I thought that's what my code is doing
  6. #4
  7. Lazy Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,280
    Rep Power
    9645
    I said "normal rules" because of that 1.19 -> 1.2 exception. If that should be going to 1.1 instead then you do want normal rules, but of truncation (aka "rounding" to zero).

    Use the standard multiply/divide trick but with Math.trunc instead of Math.round:
    Code:
    Math.trunc(value * 10) / 10
    trunc and floor are the same for positive numbers but differ for negatives: trunc rounds towards zero (-1.1 -> -1) while floor rounds to -INF (-1.1 -> -2).

    Comments on this post

    • English Breakfast Tea agrees : I don't have reputation power to give but I send u love
    Last edited by requinix; April 4th, 2017 at 03:32 AM.
  8. #5
  9. A Change of Season
    Devshed Loyal (3000 - 3499 posts)

    Join Date
    Mar 2004
    Location
    Next Door
    Posts
    3,167
    Rep Power
    220
    I am developing feelings for you.

IMN logo majestic logo threadwatch logo seochat tools logo