How can I set a minimal amount of numbers after the decimal dot (0.9=>0.90) - sql

I'm using google bigquery, and a column has values I want to round. If I do, and the rounded value ends in a zero, the zero is not displayed.
I've tried the function FORMAT, which apparently has some .number function, but I have no idea how to use it. Whenever I include any 2 things separated by a comma inside its brackets, it complains that it only takes 1 value.

You would use FORMAT() with the precision specifier. For four decimal places always -- including zeros:
select format('%.4f', 1.23)
If the BQ documentation does not answer your questions, I find that that the function seems to be inspired by the classic C printf()/sprintf() functions.

Unaware if in BigQuery (haven't used it ever) there is a better way I guess this will fix your problem since I just tried it in their console.
Cast your float to a string and then check if your last digit is a 0. In case it's not add it:
SELECT case when RIGHT(cast(0.9 as string), 1) <> '0' then cast(0.9 as string)+'0' else cast(0.9 as string) end as FormattedNumber

Related

LIKE 'x%' works, but LIKE '%x' doesn't work on INT converted to STRING

I've found this strange behaviour and I searched but couldn't find anything about it.
I know that in my example I don't need to cast [affairenum] to STRING, but because of a specific syntax in Entity Framework this is how an Affairenum.Contains(), StartsWith() or EndsWith() ends up being generated.
Consider for example a table that contains an id (affaireid column) and numbers (affairenum column) with values from 1 to 5000000.
SELECT TOP (1000) [affaireid]
,[affairenum]
,STR(affairenum) AS string
FROM [dbo].[ULAffaire]
where STR(affairenum) LIKE N'%9'
Works and returns results. Same goes with N'%9%'.
SELECT TOP (1000) [affaireid]
,[affairenum]
,STR(affairenum) AS string
FROM [Ulysse].[dbo].[ULAffaire]
where STR(affairenum) LIKE N'9%'
Does not work and returns nothing. The difference here being LIKE N'9%', the equivalent of a StartsWith().
STR(affairenum) looks identical to affairenum, EndsWith() and Contains() both work normally, but this returns nothing.
I've tried with LOWER(), to no avail. Is the STR() method adding anything ? a space, some weird character ? Am I missing something silly ?
That is because str() left pads the results with spaces. The default is a length of 10 (see here).
I'm not a fan of using numbers as strings. But if you do so, explicit conversion should do what you want:
where cast(affairnum as varchar(255)) like '9%'
That is, str() is not a type conversion function. It is a string formatting function -- hence the presence of spaces where you might not expect them.
I should note that you don't even need to explicit convert the number to a string, so this works:
where affairnum like '9%'
However, I have such bad memories of hours and hours devoted to fixing problems in SQL code that used implicit conversion, so I cannot in good conscience propose implicit conversion to someone else.

how to convert this String to Decimal

i have this String '5666,232343' and i want to convert it to Decimal, i use cast('5666,232343' as decimal(7,5)) but it returns NULL value.
Do you know why it doesn't work with CAST
Zorkolot is right. The current precision and scale that you've used is not sufficient for the value you've provided.
If you're using SQL Server 2012 or higher and you want to keep the comma in the value, then you can use the TRY_PARSE function and set a culture. It will return NULL if it encounters an error instead of not completing the statement and returning red text. This also allows you to add basic error handling to the statement, if you wanted, by getting failed conversions to return the value of zero. For example:
This is your original query (which is currently erroring) with my error handling fix:
select coalesce(try_parse('5666,232343' as decimal(7,5) using 'en-GB'),'0') as [DecimalValue]
This is the same thing as above but I've amended the decimal precision and scale so that the value is successfully converted:
select coalesce(try_parse('5666,232343' as decimal(16,6) using 'en-GB'),'0') as [DecimalValue]
This should prevent you having to perform a REPLACE either manually or by using the SQL function.
You need to cast to a decimal that can hold the value of 5666.232343.
DECIMAL(7,5) allows numbers in this format: ##.#####. The biggest number you can have then is 99.99999. You also need to take the comma out and replace it with a period:
SELECT CAST('5666.232343' as decimal(16,6)) AS [DecimalValue]
The problem is probably the comma. In some databases, some of the functions are not as internationally-sensitive as (I think) they should be. So try:
cast(replace('5666,232343', ',', '.') as decimal(7, 5))

Is format ####0.000000 different to 0.000000?

I am working on some legacy code at the moment and have come across the following:
FooString = String.Format("{0:####0.000000}", FooDouble)
My question is, is the format string here, ####0.000000 any different from simply 0.000000?
I'm trying to generalize the return type of the function that sets FooDouble and so checking to make sure I don't break existing functionality hence trying to work out what the # add to it here.
I've run a couple tests in a toy program and couldn't see how the result was any different but maybe there's something I'm missing?
From MSDN
The "#" custom format specifier serves as a digit-placeholder symbol.
If the value that is being formatted has a digit in the position where
the "#" symbol appears in the format string, that digit is copied to
the result string. Otherwise, nothing is stored in that position in
the result string.
Note that this specifier never displays a zero that
is not a significant digit, even if zero is the only digit in the
string. It will display zero only if it is a significant digit in the
number that is being displayed.
Because you use one 0 before decimal separator 0.0 - both formats should return same result.

Formatted output with leading zeros in Fortran

I have some decimal numbers that I need to write to a text file with leading zeros when appropriate. I've done some research on this, and everything I've seen suggests something like:
REAL VALUE
INTEGER IVALUE
IF (VALUE.LT.0) THEN
IVALUE = CEILING(VALUE)
ELSE
IVALUE = FLOOR(VALUE)
ENDIF
WRITE(*,1) IVALUE, ABS(VALUE)-ABS(IVALUE)
1 FORMAT(I3.3,F5.4)
As I understand it, the IF block and ABS parts should allow this to work for all values on -100 < VALUE < 1000. If I set VALUE = 12.3456, the code above should produce "012.3456" as the output, and it does. However if I have something like VALUE = -12.3456, I'm getting "(3 asterisks).3456" as my output. I know the asterisks usually shows up when there are not enough characters provided for in the FORMAT statement, but 3 should be enough in this example (1 character for the "-" and two characters for "12"). I haven't tested this yet with something like VALUE = -9.876, but I'd expect the output to be "-09.8760".
Is there something wrong in my understanding of how this works? Or is there some other limitation of this technique that I'm violating?
UPDATE: Okay I've looked into this some more, and it seems to be a combination of a negative value and the I3.3 format. If VALUE is positive and I have the I3.3, it will put leading zeros as expected. If VALUE is negative and I only have I3 as my format, I get the correct value output, but it will be padded with spaces before the negative sign instead of padded with zeros after the negative (so -9.8765 is output as " -9.8765", but that leading space breaks what I'm using the .txt file for, so it's not acceptable).
Tho problem is with your integer data edit descriptor. With I3.3 you require at least 3 digits and the field width is only 3. There is no place for the minus sign. Use I4.3 or, In Fortran 95 and above, I0.3.
Answer to your edit: Use I0.3, it uses the minimum number of characters necessary.
But finally, you just probably want this: WRITE(*,'(f0.3)') VALUE
Of course, I could get what I'm looking for by changing it up a little bit to
REAL VALUE
INTEGER IVALUE
IF (VALUE.LT.0) THEN
WRITE(*,1) FLOOR(ABS(IVALUE)), ABS(VALUE)-FLOOR(ABS(VALUE))
1 FORMAT('-',I2.2,F5.4)
ELSE
WRITE(*,2) FLOOR(VALUE), ABS(VALUE)-FLOOR(BS(VALUE))
2 FORMAT(I3.3,F5.4)
ENDIF
But this feels a lot clunkier, and in reality I'm going to try to be writing multiple values in the same line, which will lead to really messy IF blocks or complex cursor movement, which I'd like to avoid if at all possible.
as another way to skin the cat.. I'd prefer not to do arithmatic on the data at all but just work on the format:
character*8 fstring/'(f000.4)'/
val=12.34
if(val.gt.1)then
write(fstring(3:5),'(i0)')6+floor(log10(val))
elseif(val.lt.-1)then
write(fstring(3:5),'(i0)')7+floor(log10(-val))
elseif(val.ge.0)
write(fstring(3:5),'(i0)')6
else
write(fstring(3:5),'(i0)')7
endif
write(*,fstring)val
just for fun with modern fortran that supports character functions you can roll that up in a function and end up with a construct like this:
write(*,'('//fstring(val1)//','//fstring(val2)//')')val1,val2

ISNUMERIC('07213E71') = True?

SQL is detecting that the following string ISNUMERIC:
'07213E71'
I believe this is because the 'E' is being classed as a mathmatical symbol.
However, I need to ensure that only values which are whole integers are returned as True.
How can I do this?
07213E71 is a floating number 7213 with 71 zeros
You can use this ISNUMERIC(myValue + '.0e0') to test for whole integers. Slightly cryptic but works.
Another test is the double negative myValue NOT LIKE '%[^0-9]%' which allows only digits 0 to 9.
ISNUMERIC has other issues in that these all return 1: +, -,
To nitpick: This is a whole integer. It is equivalent to 7213 * 10 ^ 71.
In the documentation it says
ISNUMERIC returns 1 when the input expression evaluates to a valid integer, floating point number, money or decimal type; otherwise it returns 0. A return value of 1 guarantees that expression can be converted to one of these numeric types.
Your number is also float (with exponential notation), therefore the only way to have ISINTEGER is to define it yourself on SQL. Read the following link.
http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html
Extras:
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=59049
http://www.tek-tips.com/faqs.cfm?fid=6423
I have encountered the same problem. IsNumeric accepts "$, €, +, -, etc" as valid inputs and Convert function throws errors because of this.
Using "LIKE" SQL statement fixed my problem. I hope it'll help the others
SELECT UnitCode, UnitGUID, Convert(int, UnitCode) AS IntUnitCode
FROM [NG_Data].[NG].[T_GLB_Unit]
WHERE ISNULL(UnitType,'') <>'Department'
AND UnitCode NOT LIKE '%[^0-9]%'
ORDER BY IntUnitCode
PS: don't blame me for using "UnitCode" as nvarchar :) It is an old project :)
You have to ensure it out of the call to the database, whatever the language you work with, and then pass the value to the query. Probably the SQL is understanding that value as a string.