简体   繁体   中英

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?

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM