最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

type conversion - Convert a European Number format to US format in PhP or JavaScript - Stack Overflow

programmeradmin3浏览0评论

Imagine a number in the European number format: 1.200,64 In US format, this would be 1,200.64

How can I detect the number format and if it's European format, convert it to US format.

A solution in either JavaScript or PHP would be needed.

Imagine a number in the European number format: 1.200,64 In US format, this would be 1,200.64

How can I detect the number format and if it's European format, convert it to US format.

A solution in either JavaScript or PHP would be needed.

Share Improve this question asked Feb 15 at 23:12 CymroCymro 1,2952 gold badges11 silver badges35 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 1

You could match on the following regex pattern:

^\d{1,3}(?:\.\d{3})*,\d{2}$

and then do a replacement on such matches:

var input = "1.200.600";
var output = input.replace(/^(\d{1,3}(?:\.\d{3})*),?(\d*)$/, (x, y, z) => /,\d*$/.test(x) ? (y.replace(/\./g, ",") + "." + z) : y.replace(/\./g, ","));
console.log(input + " => " + output);

The regex pattern used here says to match:

  • ^ from the start of the input
    • ( capture in $1 (which is y in the above lambda)
      • \d{1,3}(?:\.\d{3})* match a number with dot thousands separator
    • )
    • , match comma as decimal separator
    • ( capture in $2 (which is z in the above lambda
      • \d{2} two digit decimal
    • )
  • $ end of input
发布评论

评论列表(0)

  1. 暂无评论