Adding trailing and leading zeroes - sql

How do we convert and add trailing and leading zeros to a number? For example 123.45. I need to make this ten digits long and have padding numbers in front and back. I would like to convert it to 0001234500. Two trailing numbers after the last digit of the decimal. Remove the decimal. Fill in the remaining space with zeroes for the leading end.
I have this so far and it adds trailing zeroes and removes the decimal.
REPLACE(RIGHT('0'+CAST(rtrim(convert(char(10),convert(decimal(10,4),Field))) AS VARCHAR(10)),10),'.','') as New_Field

In MySQL you would have RPAD and LPAD to get stuff like this done, in SQL Server (2012+) you can get something similar by working with FORMAT.
Easiest way is to FORMAT your numbers with a dot so that they take the right place in the format string, then remove that dot. You need to specify a locale, since in different regions you will get a different decimal sign (even if you use . within the format pattern, you would get , in various locales) - using en-US makes sure you get a dot.
REPLACE(FORMAT(somenumber, '000000.0000', 'en-US'), '.', '')
A few examples:
WITH TempTable(somenumber) AS (
SELECT 3
UNION SELECT 3.4
UNION SELECT 3.45
UNION SELECT 23.45
UNION SELECT 123.45
)
SELECT
somenumber,
REPLACE(FORMAT(somenumber, '000000.0000', 'en-US'), '.', '')
FROM
TempTable;
Gives
3.00 0000030000
3.40 0000034000
3.45 0000034500
23.45 0000234500
123.45 0001234500

You seem to really be overthinking what you need to do here. If we take it in steps, perhaps you'll see that this can be achieved much more easily. This solution runs under the idea that the value 123.45 becomes 0001234500 and 6.5 becomes 0000065000.
Firstly, let's pad out the right hand side of the number 123.45 so that we have 1234500 That's easy enough : 123. 45 * 100 = 12345 So, to get 1234500 we simply need to multiple it by a couple of extra factors of 10:
SELECT 123.45 * 10000; --1234500.00
Ok, now, let's get rid of those decimal places. Easiest way, convert it to an int:
SELECT CONVERT(int, 123.45 * 10000); --1234500
Nice! Now, the finalstep, the leading 0's. A numerical value, in SQL Server, won't display leading zeros. SELECT 01, 001.00; Will return 1 and 1.00 respectively. A varchar however, will though (as it's not a number). We can, therefore, make use of that with a further conversion, and then then use of RIGHT:
SELECT RIGHT('0000000000' + CONVERT(varchar(10),CONVERT(int,123.45 * 10000)),10);
Now you have the value you want '0001234500'.
If you're only after padding, (so 6.5 becomes 0006500) then you should be able to work out how to achieve this with the help above (hint you don't need RIGHT).
Any questions, please do ask.

Related

Format from decimal to money SQL Server 2019

I need this type of decimal number format because what I show refers to money. SP SQL Server 2019
I need to transform from this $25,000.00 a $25.000,00.
Someone could help me?
REPLACE(REPLACE(CONVERT(varchar,CAST(#MontoFinal AS money),1),'.',','),',','.') = 117.692.05
Formatting is usually best handled by the UI, but sometimes you have to do it in the database for various reasons. Sometimes you have to live with mandates, and if you have to do it in the database, it can be done.
Looking at your desired output, you want periods as separators and a comma as a decimal point, and you would also like a dollar sign. Luckily for you, this is how Argentina formats its currency, so you can just use the built-in FORMAT function. The culture string for Argentina is es-AR, so you can use that along with FORMAT:
SELECT FORMAT(123456789, 'C', 'es-AR') AS [Example];
This yields:
Example
$ 123.456.789,00
If your data is a number, you are done. If it is stored as text like in your example, you can CAST it as you were doing:
SELECT FORMAT(CAST('$25,000.00' AS MONEY), 'C', 'es-AR') AS [Example];
Which gives your desired output:
Example
$ 25.000,00
As a final note, the FORMAT function in this scenario puts a space between the dollar sign and the leading number - if you don't want the space, you can remove it:
SELECT REPLACE(FORMAT(CAST('$25,000.00' AS MONEY), 'C', 'es-AR'), ' ', '') AS [Example];
And that gives you:
Example
$25.000,00
There are other ways to get a similar result, but this is probably the easiest (I said easiest, I did not say anything about performance).
If your data is actually text and already has the correct commas and decimal points along with the dollar sign, you could use REPLACE - first replace . with something (I used _), then REPLACE the , with ., and finally REPLACE the _ with . :
SELECT REPLACE(REPLACE(REPLACE('$25,000.00', '.', '_'), ',', '.'), '_', ',') AS [Example];
And again it gives your desired output:
Example
$25.000,00
If your data is not in a consistent format to start with correct commas and decimal points, the FORMAT approach will probably work better for you.

How can I format the decimal value without decimal?

eg 18.45 should be 00000000001845000
datatype suppose number(x,5) so last five digits are for precision
Another option is to use the V format model element; from the documentation:
Element
Example
Description
V
999V99
Returns a value multiplied by 10n (and if necessary, round it up), where n is the number of 9's after the V.
So you can do:
select to_char(18.45, '000000000000V00000') from dual;
TO_CHAR(18.45,'000000000000V00000')
-----------------------------------
00000000001845000
or without the leading space (which is a placehold for a minus sign in case there are negative values):
select to_char(18.45, 'FM000000000000V00000') from dual;
TO_CHAR(18.45,'FM000000000000V00000')
-------------------------------------
00000000001845000
db<>fiddle
Also you can multiply for 100000 the given number:
SELECT TO_CHAR(18.45 * 100000, '00000000000000000') FROM DUAL;
This should do it:
SELECT REPLACE(TO_CHAR(18.45, 'FM000000000000D00000', 'NLS_NUMERIC_CHARACTERS=''.,'''), '.', '') FROM DUAL;
The NLS_NUMERIC_CHARACTERSmakes sure the decimal separator is a . regardless what the session is configured. This way we're safe to remove it from the resulting string with the replace function.
The FM is used to suppress the leading space character.

Format query to show floating decimal in Oracle SQL

I am using Oracle SQL Developer and I have a query in which one of the columns has a number value that I want to divide by 1,000,000 then display to show commas and up to 10 decimal places if the calculate value has any decimal places. I am currently using this query:
to_char(value/1000000, 'FM999,999,990.9999999999') as Millions_Value
The above format gives me commas and retains the number of decimal places I want, but it unfortunately adds a decimal point at the end of whole numbers as well.
Example:
value/1000000 = 33993
formatted value = 33,993.
what I want = 33,993
For a decimal value, I get what I want and need to keep the format
Example:
value/1000000 = 0.158739
formatted value = 0.158739
value/1000000 = 10.82
formatted value = 10.82
And ideas on how to get rid of the decimal for integers?
The easiest way is to use RTRIM, e.g.
RTRIM(to_char(value/1000000, 'FM999,999,990.9999999999'), '.') as Millions_Value
will remove any trailing periods.
EDIT
If you want to get fancy and internationalize it you need to query NLS_SESSION_PARAMETERS to get the decimal separator, use the G (group) and D (decimal) specifiers in the format string, and then trim off any trailing decimal separator characters. Or in other words:
WITH cteData AS (SELECT 123456789.123456789 AS N FROM DUAL UNION ALL
SELECT 123 FROM DUAL),
cteDecimalSeparator AS (SELECT SUBSTR(VALUE, 1, 1) AS DECIMAL_SEPARATOR
FROM NLS_SESSION_PARAMETERS
WHERE PARAMETER = 'NLS_NUMERIC_CHARACTERS')
SELECT TO_CHAR(N, 'FM999G999G990D9999999999') AS OLD_FORMAT,
RTRIM(TO_CHAR(N, 'FM999G999G990D9999999999'), s.DECIMAL_SEPARATOR) AS NEW_FORMAT
FROM cteData d
CROSS JOIN cteDecimalSeparator s
which returns
OLD_FORMAT NEW_FORMAT
123,456,789.123456789 123,456,789.123456789
123. 123
Remember: there's no kill like overkill :-)
Personally, I think it looks good with one trailing 0, so converting your format string to have a 0 after the decimal. But to answer you question, I think you just need to trim it after you convert the number like this:
SELECT TRIM(TRAILING '.' FROM TO_CHAR('345676', 'FM999G999G990D9999999999'))
FROM DUAL;

SQL to_char() printing 2 digit number as 0xx and not touching 3 number digit

I'm currently battling with something
that must be trivial for you.
I have 2 number 191 and 97, and I need to put them in a SQL request, as chars and 97 must be printed as 097.
At first I tried 999, but it added 2 space to my numbers.
then 099, it does print 097 but it adds a space to it.
to_char(:center, '099') = " 197" and " 097"
Where is this space coming from?
Thanks.
What you're looking for is the Format Modifier element:
to_char(:center, 'fm099')
The leading space is for the potential minus sign. To remove it you can use FM in the format:
to_char(v_num,'FM099')
9 9999 Returns value with the specified number of digits with a leading space if positive or with a leading minus if negative.Leading zeros are blank, except for a zero value, which returns a zero for the integer part of the fixed-point number.
From http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm#i34510
Use #DavidAldridge solution, or trim your value.
If you are looking for the all column values in same number of digits even the actual value having less digits. Try this
a) SELECT TO_CHAR(COLUMN_NAME, 'FM099') FROM TABLE_NAME;
b) SELECT TO_CHAR(COLUMN_NAME, 'FM000') FROM TABLE_NAME;
Both is working fine. but don't know which one would be the best choice.

TOAD SQL - LPAD Number, but also add decimals?

Basically what I'm trying to do is add '000' to a number (between 5-8 characters in length) and make the whole numbers have decimals.
What I came up with is:
SELECT DISTINCT
'000' || TO_CHAR(Blah, '9,999,999.99') AS "Data"
FROM Blah database
While this does what I ideally want, there is a gap between the zeroes of either 3 or 4 depending on the number. Obviously I don't want the gap there. Where am I going astray?
Use trim(to_char(x, '9,999,999.99')) this way you will avoid gap