How do I parse a string with a decimal point to a double?

前端 未结 19 1561
孤街浪徒
孤街浪徒 2020-11-22 06:47

I want to parse a string like \"3.5\" to a double. However,

double.Parse(\"3.5\") 

yields 35 and

double.Pars         


        
19条回答
  •  深忆病人
    2020-11-22 07:03

    I improved the code of @JanW as well...

    I need it to format results from medical instruments, and they also send ">1000", "23.3e02", "350E-02", and "NEGATIVE".

    private string FormatResult(string vResult)
    {
      string output;
      string input = vResult;
    
      // Unify string (no spaces, only .)
      output = input.Trim().Replace(" ", "").Replace(",", ".");
    
      // Split it on points
      string[] split = output.Split('.');
    
      if (split.Count() > 1)
      {
        // Take all parts except last
        output = string.Join("", split.Take(split.Count() - 1).ToArray());
    
        // Combine token parts with last part
        output = string.Format("{0}.{1}", output, split.Last());
      }
      string sfirst = output.Substring(0, 1);
    
      try
      {
        if (sfirst == "<" || sfirst == ">")
        {
          output = output.Replace(sfirst, "");
          double res = Double.Parse(output);
          return String.Format("{1}{0:0.####}", res, sfirst);
        }
        else
        {
          double res = Double.Parse(output);
          return String.Format("{0:0.####}", res);
        }
      }
      catch
      {
        return output;
      }
    }
    

提交回复
热议问题