简体   繁体   中英

JavaScript regex - Format decimal with trailing zero and string

I have different format of prices, which needs to be displayed as below:

1.09-----> 1.09
1.00----> 1
1.00 lb --->1lb
1.09 lb---->1.09lb

I need help in building the regex for JavaScript to display the above prices in specified formats.

Parse and format the numeric portion using parseFloat and Number.toString . Add a special case to handle LBs:

function formatPrice(price) {
    return parseFloat(price) + (price.match(/ .+$/) ? price.match(/ (.+)$/)[1] : "");
}

console.log(formatPrice("1.00"));    // 1
console.log(formatPrice("1.09"));    // 1.09
console.log(formatPrice("1.09000")); // 1.09
console.log(formatPrice("1.00 lb")); // 1lb
console.log(formatPrice("1.09 lb")); // 1.09lb
console.log(formatPrice("1.09 kg")); // 1.09kg

You could try the below regex,

> "1.09 lb".replace(/\.00|\s+/g, "");
'1.09lb'
> "1.00 lb".replace(/\.00|\s+/g, "");
'1lb'
> "1.00".replace(/\.00|\s+/g, "");
'1'
> "1.09".replace(/\.00|\s+/g, "");
'1.09'

To remove more than two zero's,

> "1.000".replace(/\.00+|\s+/g, "");
'1'

You can try

\.0+\s*(\D*)$|[ ]+

Replacement : $1

Here is online demo

Sample code:

var re = /\.0+\s*(\D*)$|[ ]+/g;
var str = '1.09\n1.00\n1.00 lb\n1.09 lb';
var subst = '$1';

var result = str.replace(re, subst);

output:

1.09
1
1lb
1.09lb

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