NaN替换为非数字值

NaN替换为非数字值

本文介绍了如何将字符串数组转换为浮点数组,并将Double.NaN替换为非数字值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为CSV数据编写解析器,并试图确定如何处理记录为空白(")或包含字符数据("C").我下面的解析器代码很好用,但是迫使我稍后处理浮点转换.我希望能够使我的string [] []成为float [] [],并在解析文件时处理转换,但是我注意到它会与所有非数字数据一起爆炸.理想情况下,不会有非数字或空白值,但它们是不可避免的,因此必须加以处理.

I'm writing a parser for CSV data, and am trying to determine how to handle recordsthat are blank ("") or contain character data ("C"). The parser code I have below works great, but forces me to deal with the float conversions later. I'd like to be able to just make my string[][] a float[][], and handle the conversions when I parse the file, but I notice that it blows up with any non-numeric data. Ideally there would be no non-numeric or blank values, but they are unavoidable, and as such, have to be dealt with.

有人可以推荐一种简洁的方法来尝试转换为Double,然后如果不起作用,请改为使用Double.NaN代替? (如果可能,不牺牲很多性能).谢谢.

Can someone possibly recommend a concise approach to attempt to convert to Double, and then if it doesn't work, replace with Double.NaN instead? (Without sacrificing much performance if possible). Thank you.

let stringLine = [| "2.0"; "", "C"|]
let stringLine2Float = Array.map float stringLine

//desiredFloatArray = [| 2.0; Double.NaN; Double.NaN |]


type csvData = { mutable RowNames: string[]; mutable ColNames: string[]; mutable Data: string[][] }

let csvParse (fileString: string) =
    let colNames = ((fileLines fileString |> Seq.take 1 |> Seq.nth 0).Split(',')).[1..]
    let lines = fileLines fileString |> Seq.skip 1 |> Array.ofSeq
    let rowNames = Array.init lines.Length string;
    let allData : string [][] = Array.zeroCreate rowNames.Length

    for i in 0..rowNames.Length - 1 do
        let fields = lines.[i].Split(',')
        allData.[i] <- fields.[1..]
        rowNames.[i] <- fields.[0]

    { RowNames = rowNames; ColNames = colNames; Data = allData }

推荐答案

使用此方法代替内置的float转换:

Use this instead of the built-in float conversion:

let cvt s =
  let (ok,f) = System.Double.TryParse(s)
  if ok then f else nan

这篇关于如何将字符串数组转换为浮点数组,并将Double.NaN替换为非数字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 03:01