Question: I Need to add comma operator for number when typing and restrict 2 decimal places

Question

I Need to add comma operator for number when typing and restrict 2 decimal places

Answers 1
Added at 2017-01-04 12:01
Tags
Question

I am trying to add $123,123.12 comma format and restrict the decimal to two places can anyone please help with regex. I have tried like this. I have a input box now when I enter it comes as 1231244 but I need like $123,123.12 how to make a function to achieve this can you help with the code.

<input type="text" value="$0.00" step="0.01"/>
Answers
nr: #1 dodano: 2017-01-04 12:01

Please, take a look at this below code:

var value ="1231244"
var lasttwovalue = value % 100;
var firstValue= parseInt(value.slice(0,-2))
if(lasttwovalue >50)
{
   lasttwovalue = '00';
   firstValue = firstValue + parseInt(1)
}
console.log('$'+ firstValue.toLocaleString() + '.' + lasttwovalue)

//result is $12,313.00 if value is 1231255
//result is $12,312.44 if value is 1231244

Working demo on jsfiddle

Source Show
◀ Wstecz