CAST and CONVERT rounded a float by passing it to varchar - SQL SERVER 2014 - Microsoft SQL Server Management Studio version 12.0.2269.0

1

Good afternoon, I have a problem when I take the float values from a sql server database and convert them to varchar with CONVERT. This function, I round the float and then it turns it rounded. The same goes for CAST. I need the varchar to be a true copy of the float number (with all the decimals). Probe putting in each function the value from one variable (that's where it rounds and without variable where it does not round it.) I'll attach an example.

As an achievement, do not round it up if the value is in a variable ???? Thank you very much.

    
asked by Osky 06.12.2017 в 17:33
source

2 answers

1

The main problem is that the type of data you want to convert is float , which is an approximate numeric data type. Since you are using SQL Server 2014, you have the FORMAT function available:

DECLARE @flo float = -34.6919581;

SELECT FORMAT(@flo,'G');

The result is -34.6919581 in string format.

Here is a demo of this.

    
answered by 06.12.2017 / 17:53
source
0

As Lamak says, the float is an approximate data if you need to maintain a precision you should modify the type to decimal for example a decimal(15,8) . To complement, you have some other options. Let's see some:

This function can be configured with the parameter style of float a 128

CONVERT(VARCHAR, @flo, 128)

Important : Do not use this form, I only indicate it for information purposes, according to the documentation 126, 128, 129 Included for legacy reasons and might be deprecated in a future release.

  • CAST previous to decimal

You can previously "cast" the float to decimal with the accuracy you are looking for, for example:

CAST(CAST(@flo AS DECIMAL(15,8)) AS VARCHAR(30))

Surely this option is the best for old versions of SQL server , it is not your case.

This function is available from version 2008 and gives better control over the representation in characters of a float since it allows to establish length and precision:

STR(@flo, 15,8)

Of all the forms I am still staying with the proposal of Lamak since you do not add 0 to the left, example:

DECLARE @flo FLOAT = -34.6919581

SELECT  CONVERT(VARCHAR, @flo, 128),
    CAST(CAST(@flo AS DECIMAL(15,8)) AS VARCHAR(30)),
    STR(@flo, 15,8), 
    FORMAT(@flo,'G')

CONVERT       CAST DECIMAL  STR             FORMAT
------------ -------------- --------------- -----------
-34.6919581    -34.69195810    -34.69195810 -34.6919581
    
answered by 06.12.2017 в 18:25