代码之家  ›  专栏  ›  技术社区  ›  SqlLearner

如何在sql中将负数转换为正数

  •  0
  • SqlLearner  · 技术社区  · 2 年前

    我想将-2.07转换为207,但使用ABS(),如图所示;它返回200而不是207。 请帮我理解我在这里错过了什么。谢谢

     declare @ReimbursementCents int,
     @journey_fare numeric(7,2)
     SET @journey_fare = -2.07
    
     SET @ReimbursementCents = convert(int,ABS(@journey_fare)) * 100
     if (@ReimbursementCents > 0)
     print @ReimbursementCents
    
    1 回复  |  直到 2 年前
        1
  •  0
  •   superdev    2 年前

    看起来问题在于运算的顺序和乘以100的位置。目前,您正在将@swage_fare的绝对值转换为一个整数,然后将其乘以100,这可能会给负值带来意外的结果。

    要实现使用ABS()将-2.07转换为207的期望结果,您应该首先乘以100,然后转换为整数。 以下是更正后的代码:

    DECLARE @ReimbursementCents INT,
            @journey_fare NUMERIC(7,2);
    
    SET @journey_fare = -2.07;
    
    -- Multiply by 100 and then convert to integer
    SET @ReimbursementCents = CONVERT(INT, ABS(@journey_fare) * 100);
    
    IF (@ReimbursementCents > 0)
        PRINT @ReimbursementCents;
    

    现在,该代码将正确地输出207,用于给定的@swage_fare值-2.07。关键变化是在应用ABS()函数之前乘以100。