【问题标题】:What is C# equivalent of SQL function STR?SQL 函数 STR 的 C# 等效项是什么?
【发布时间】:2015-10-04 08:17:12
【问题描述】:

我在 SQL 中有以下代码:

declare @test numeric(19,15)    = 219.37345462345234235
SELECT str(@test,9,9) -- 219.37345

declare @test numeric(19,15)    = 19.37345462345234235
SELECT str(@test,9,9) -- 19.373455

declare @test numeric(19,15)    = 9.3
SELECT str(@test,9,9) -- 9.3734546

我怎样才能在 C# 中实现这一点,说我有

double  d = 219.37345462345234235;

无论输入是什么,所需的输出都应包含 9 个字符,如以下示例中所示

下面的代码sn-p给出结果

public static string GetFormat(double quantity)
    {
        quantity = Math.Round(quantity,9-(Math.Truncate(quantity).ToString().Length));
        string customQuantity = quantity.ToString().PadRight(9, '0');

        if (customQuantity.Length > 9)
            customQuantity = customQuantity.Substring(0, 9);
        else if (customQuantity.Length == 9 && customQuantity.EndsWith("."))
            customQuantity = customQuantity.Substring(0, 8);

        return customQuantity; 
    }

这可以以更好的方式实现吗? 谢谢

【问题讨论】:

标签: c# sql double substring


【解决方案1】:
public static string GetCustomStringQuantity(double quantity)
    {
        string customQuantity ;
        quantity = Math.Round(quantity, 9 - ((int) Math.Log10(Math.Abs(quantity))+1),MidpointRounding.AwayFromZero);            
        customQuantity = quantity.ToString();  
        customQuantity= (quantity %1==0)?(customQuantity+".").PadRight(9, '0'):customQuantity.PadRight(9, '0');            

        if (customQuantity.Length > 9)
            customQuantity = customQuantity.Substring(0, 9);
        else if (customQuantity.Length == 9 && customQuantity.EndsWith("."))
            customQuantity = customQuantity.Substring(0, 8);

        return customQuantity; 
    }

这对我有用。但我不确定这是否是优化代码。

【讨论】:

    猜你喜欢
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多