In AutoNumeric javascript, how do I create a format that shows integer if the input is an integer but currency if the input is a float?

199 views Asked by At

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.

2

There are 2 answers

1
Vladyslav Tymoshchyk On

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

(23.2).toFixed(2); // 23.20
1
S. Imp On

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)
}