question

akhterhussain-3167 avatar image
0 Votes"
akhterhussain-3167 asked ErlandSommarskog answered

two digits after decimal ?

I want two digits after decimal.

 cast(B.Bweight as decimal(10,2))/cast(C.iWeight as decimal(10,2))*100 [Percentage]


currently i am getting below result

0.9021512838300
but i want

0.90

sql-server-generalsql-server-transact-sql
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

ErlandSommarskog avatar image
0 Votes"
ErlandSommarskog answered

The resulting data type when you perform an operation on two decimal values is a complicated story, and I don't remember the rules by hart. But as you have experienced, dividing two decimal(10,2) values does not result in a new decimal(10,2) value.

I would write this as

cast(     cast(B.Bweight as float)/cast(C.iWeight as float)*100 as decimal(10,2)) AS [Percentage]

The reason I would cast to float before the division is that this the best accuracy for the division as such. But depending on the actual data types of the Weight columns, this may be an over kill. The important is that you need to cast the final result to decimal(10,2).

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.