简体   繁体   中英

regex expression to convert currency format

I am using a regex expression for converting user input into currency format, but I don't know how it works. I am learner in Regex Help me.

    return "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")

I also need negative numbers to be in currency format how can i achieve this?

    example
        -254182=> -254,182.00

Let's break it apart:

"$"                                       # literal $ sign
num.toFixed(2)                            # round up to 2 decimal points
replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,") # places comma after every 3 digits

Placement of comma after every 3 digits is done using a lookahead regex that asserts that there are 1 more sets of 3 digits ahead finally followed by a non-digit.

Example:

var num = 1234567.8685;
var fmt = "$" + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,")
//=> $1,234,567.87

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