0

I want to validate a textbox which rounds to two decimal places. However, I do not want to round up.

For example; if I enter 19.999 then the result will be 19.99, not 20.00

And if I enter 19.7, then result will be 19.70. If I enter 19, then result will be 19.00

The toFixed() function is not working in my code.

Can someone please help me with this?

Johnny Bones
  • 8,786
  • 7
  • 52
  • 117
Sanjeev
  • 1,087
  • 8
  • 18
  • 27

4 Answers4

0

try working like,

parseInt(19.999 * 100)/100

for if you want to get 19.7 to 19.70 use following,

var num = parseInt(19.7 * 100).toString();
num = num.substring(0,num.length-2) +"."+ num.substring(num.length-2,num.length);
niksvp
  • 5,545
  • 2
  • 24
  • 41
0
var string = "19.99999";
var newString = string.split(string.indexOf('.') + 2)[0];
chrisfrancis27
  • 4,516
  • 1
  • 24
  • 32
0
function withPrec(number, digitsAfterComma) {
    if (digitsAfterComma <= 0 || digitsAfterComma > 10) return number; // bad args
    var str = String(number);
    var comma = str.indexOf('.');
    var zeroes = '0000000000'.substring(0, digitsAfterComma);
    return (comma == -1) ? 
        str + '.' + zeroes : (str + zeroes).substring(0, comma + digitsAfterComma + 1);
}    

Using substring to avoid building an intermediate array.

Use as withPrec(10.00001, 2) or withPrec(1, 5);

tucuxi
  • 17,561
  • 2
  • 43
  • 74
0

Better answer in other questions: use Number(aNumber).toFixed(2)

Community
  • 1
  • 1
tucuxi
  • 17,561
  • 2
  • 43
  • 74