Reputation: 1800
I am having a currency value with comma and dot. I need to change some European style currency to UK style value.
11,200.00 -> 11200.00
11.200,00 -> 11200.00
58.20 -> 58.20
58,20 -> 58.20
2500 -> 2500
I have tried using right() and replace functions but no luck.
Could anyone please help me in writing replace function to handle this.
Upvotes: 1
Views: 1308
Reputation: 13049
This is an issue in European countries, especially when new and legacy software have to co-exist. If "European style currency values coming in" from an external source then you have no other choice but handle them. First try to determine which style the string value belongs to with regexp matching and then do the relevant correction. Something like this illustration:
select case
when :strval ~ '^[+-]?(\d+\.)*\d+(,\d+)$' then replace(replace(:strval, '.', ''), ',', '.')
when :strval ~ '^[+-]?(\d+,)*\d+(\.\d+)$' then replace(:strval, ',', '')
when :strval ~ '^[+-]?\d+$' then :strval
-- maybe there are other formats so the list may grow
end;
As a function:
create or replace function unify_numeric_format(strval text)
returns numeric language sql immutable as
$$
select case
when strval ~ '^[+-]?(\d+\.)*\d+(,\d+)$' then replace(replace(strval, '.', ''), ',', '.')
when strval ~ '^[+-]?(\d+,)*\d+(\.\d+)$' then replace(strval, ',', '')
when strval ~ '^[+-]?\d+$' then strval
-- maybe there are other formats so the list may grow
end::numeric;
$$;
Upvotes: 3
Reputation: 23686
To solve this specific problem, I would make two replace()
steps:
SELECT replace(replace('11.200,00', '.', ''), ',', '.')
Nonetheless, you should take the comment of @a_horse_with_no_name serious: Don't store values as a type text
.
Edit: Wait, you have both variants: 11.200,00
AND 11,200.00
? You have to normalize this table. Please switch the column type to numeric
.
Upvotes: 1