javascript dealing with numbers - need to check for decimal places and then round

I have a variable being computed through my code. This number can be a whole number or an integer with decimal places. My requirement is simple.

  1. If the number is whole and has either one decimal or 2 decimal places, leave the number as it is.
  2. If the number has more than 2 decimal places then round it to 2 decimal places.

Can someone guide me with this?

2 answers

  • answered 2020-06-27 04:19 Ghost

    You can use toFixed function of js to round off a number.

    var computed = 2.414132
    var rounded = computed.toFixed(2)

    You can use the following logic to convert the num into string, then split into array to check if it has more than 2 decimal places or is a whole number.

    let check = computed.toString().split('.');
    if (check.length == 1) {
        // Whole num
    else {
        if (check[1].length > 2) {
            //Decimal with more than 2 decimal places, so use toFixed()

  • answered 2020-06-27 04:23 hev1

    You can use toFixed along with the unary plus operator.

    let num = 12.367;
    num = +num.toFixed(2);//12.37