Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
how can we store in 'which data type' only two num after decimal and not roundoff the num in sql 


What I have tried:

I have data num like 2.7777
i need onlt two num after decimal without roundoff
if i storing this num in float or decimal this data type round off the num like 2.78
desired output is 2.77
Posted
Updated 28-Jan-19 0:36am

You are wrong about float.

The following code snippet
SQL
create table test (a1 float, a2  decimal(15,2), a3  numeric(15,2), a4 real)
insert into test values (2.7777,2.7777,2.7777,2.7777)
select * from test
produces the results
2.7777	2.78	2.78	2.7777
But if I change the definition of a2 and a3
SQL
create table test2 (a1 float, a2  decimal(15,4), a3  numeric(15,4), a4 real)
insert into test2 values (2.7777,2.7777,2.7777,2.7777)
select * from test2
gives
2.7777	2.7777	2.7777	2.7777
To get your desired result of 2.77 then you can use ROUND [^] forcing it to truncate. Compare these results from
SQL
select round(a1, 2), round(a1, 2, 1), round(a2, 2), round(a2, 2, 1), round(a3, 2), round(a3, 2, 1), round(a4, 2), round(a4, 2, 1) from test2 
which gives the results (I've added vertical bars to make it easier to see each column
2.78	2.77 |	2.7800	2.7700 | 2.7800	2.7700	| 2.78	2.77
You should really be doing the truncation in your presentation layer though.

In summary then, store your data in a column of type float, decimal (with enough digits right of the decimal point defined), numeric (comment as for decimal) or real and either truncate it in the UI or use
SQL
ROUND(yourColumnName, 2, 1)
 
Share this answer
 
use datatype decimal(18, 2)

eg.
SQL
declare @dig decimal(18, 2) = 2.7777
    select @dig


return
2.77
 
Share this answer
 
Comments
CHill60 29-Jan-19 8:09am    
Incorrect. If I run your code I get a result of 2.78 which is the exact opposite of what the OP wanted. I demonstrated this in my solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900