1

I need to create a format in AutoNumeric javascript that does the following:

If the textbox's input value is 87, leave it unformatted: 87

If the input value is 87.6, show it as: 87.60

If the input value is 87.65, show it as: 87.65

If the input value is 87.654, show it as: 87.654

If the input value is 87.6543, round it down or truncate it: 87.654

If the input value is 87.65432, again, round it or truncate it to 87.654

I have it all worked out except for the situation where the input value is 87.6. The formatted value remains 87.6, but I want it to be 87.60, because it's a currency that can have 2 or more decimal places, but never just 1.

Ringo
  • 5,097
  • 3
  • 31
  • 46

2 Answers2

1

If you do those manipulations in pure JavaScript you can use Number.prototype.toFixed

(23.2).toFixed(2); // 23.20
1

Not sure what you mean by 'I have to use AutoNumeric' -- perhaps you could elaborate in your original post to clarify?

Otherwise, you can use regex to check for a single decimal and then use Number.toFixed() to make sure it has 2 decimal points if there's only one.

let v = 87.6

var regexp = /^\d+\.\d{1}$/;

// returns true
if (regexp.test(v)) {
  v = v.toFixed(2)
}
S. Imp
  • 2,833
  • 11
  • 24
  • 1
    It's a question about how to do something in AutoNumeric. We use AutoNumeric for all our numeric input fields in all our forms, dozens of them, and AutoNumeric tracks and manages the fields in our single page application. Deciding not to use it for certain numeric fields isn't really feasible. We've drunk the kool aid. But I think I have a solution involving changing field options on the fly using the autonumeric api. – Ringo Jan 22 '23 at 04:45