How to make a REGEX statement that will allow interpretation of EU and US decimal notations

流过昼夜 提交于 2020-01-21 19:00:12

问题


I have been working on a tough question and gotten a lot of help from programmers and developers on this site. Many thanks to those who contribute. You are invaluable.

Using Javascript and HTML. I am a newbie.

The current condition of my problem is this...

I am attempting to develop a metric to english conversion website that takes a numeric value in a HTML textbox (no form):

I want the user to have multiple ways of entering the data into the conversion tool as it will be used internationally. So...

1,200 or 1.200 or 1200 should all be interpreted by parseFloat as 1200.00

1,200.12 or 1.200,12 or 1200.12 or 1200,12 should all be interpreted as 1200.12.

I would also like decimals to be able to be interpreted. 0.123 or 0,123
as 0.123

I realize that I need to strip the thousand seperators out (whether comma or period) and set the final decimal to a period if it is a comma. A developer on this site gave me a REGEX statement that I could use in conjunction with a javascript replace statement to handle this.

trim = trim.replace(/[.,](?=.*[.,])/g, "").replace(",", "."); 
//care of recursive on stack overflow

This seemed to solved the problem with one exception. Anytime data is entered using a thousand separator without using a decimal point this code interprets the separator as a decimal and the value goes from 12,345 to 12.345 or (EU Notation as well). Assuming that the user will use commas but no decimals, this is a troublesome problem as the results will not be correct. How am I to remedy this? Is there an adjustment I can make to the REGEX to have it determine when a comma is a thousand separator (1.234) or a decimal (1,234), or when a period is a thousand separator (1,234) or a decimal point (1.234)?

Thanks in Advance,

RP

来源:https://stackoverflow.com/questions/25437910/how-to-make-a-regex-statement-that-will-allow-interpretation-of-eu-and-us-decima

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!