Home > Enterprise >  How to convert octa to decimal in postgres
How to convert octa to decimal in postgres

Time:08-19

Only found this related answer: Convert octal to decimal in SQL

Based on https://www.rapidtables.com/convert/number/octal-to-decimal.html?x=0325,
Octal: 0325 should convert to decimal 213.

CodePudding user response:

The accepted answer from the SQL Server question can be converted to Postgres. It's actually a bit easier as you can split the string directly into the letters using string_to_table

create function octal_to_decimal(p_input text)
  returns numeric
as
$$  
  select sum(x.digit::int * 8 ^ (length(p_input) - idx)) as val
  from string_to_table(p_input, null) with ordinality as x(digit, idx) 
$$
language sql
stable;

select octal_to_decimal('0325') returns 213

If you are on an older Postgres release, you need to replace string_to_table(p_input, null) with unnest(string_to_array(p_input, null))

  • Related