Home > Blockchain >  How can I get only the first decimal of a number but without rounding it
How can I get only the first decimal of a number but without rounding it

Time:11-16

What I have is : 1.88 or 2.488 and what I want is 1.8 and 2.4

So basically, I want only the first digit of the decimal but without rounding it.

I tried to use floor but it only gives me the number without the decimal. And I found some solutions on Internet but every solution round the number.

CodePudding user response:

You can use this :

sELECT CAST (ROUND(2.488888 , 1, 1) AS decimal(18,1))

enter image description here

sELECT CAST (ROUND(2.4999999 , 1, 1) AS decimal(18,1))

enter image description here

CodePudding user response:

Use Round() function with third parameter.

ROUND(1.88, 2 ,1)

this function has the following parameters.

ROUND(number, decimals, operation)

  • number Required. The number to be rounded
  • decimals Required. The number of decimal places to round number to
  • operation Optional. If 0, it rounds the result to the number of the decimal. If another value than 0, it truncates the result to the number of decimals. The default value is 0

Related link on W3School :- LINK

CodePudding user response:

You can tackle this a few different ways. You could convert to character data or do some integer math.

declare @Nums table
(
    SomeNumber decimal(7,4)
)

insert @Nums
select 1.88 union all select 2.488

select *
    , left(SomeNumber, charindex('.', convert(varchar(10), SomeNumber))   1)
    , convert(decimal(7,1), convert(int, SomeNumber * 10) / 10.0)
from @Nums
  • Related