divHelper11
divHelper11

Reputation: 2208

Cut the decimals in a number

I have seen some topics on truncating decimals. To be honest I do not know exactly how to do this in my example and I dont fully understand it.

$("#doZaplatyDollar").html((openTotal + pok1 + pok2 + pok3)/3.86513762);

It gives me numbers like 82.124124123 and I just need 82.12 Please help me with this one

Upvotes: 0

Views: 134

Answers (2)

ottis
ottis

Reputation: 216

To stop rounding of toFixed you could write a method like:

function toFixedWithoutRound(num, precision) {
    return Math.floor(num * Math.pow(10, precision)) / Math.pow(10, precision);
}

Using something like that should return what you're looking for e.g.

// should output 82.12
toFixedWithoutRound(82.125124123, 2);

Hope that helps...

Upvotes: 1

nils
nils

Reputation: 27174

If you just want to trim it, you could turn the Number into a String and use a regex to replace the last parts:

var val = (openTotal + pok1 + pok2 + pok3)/3.86513762;
val = val.toString().replace(/^(\d+\.\d{2}).*$/, '$1');
$("#doZaplatyDollar").html(val);

If you want to trim it using mathematical functions, you could do it with Math.floor:

var val = (openTotal + pok1 + pok2 + pok3)/3.86513762;
val = Math.floor(val * 100) / 100
$("#doZaplatyDollar").html(val);

Upvotes: 2

Related Questions