dougong1031 2019-08-31 02:40
浏览 53

go中是否有一个atof等效项?

When converting the string "3px" to a float, C is able to handle it but go does not. In go, is there a way to convert the longest valid prefix of a string to a float?

C:

#include <stdlib.h>
#include <stdio.h>

int main() { 
    printf("%f", atof("3px")); 
    // result: 3.0
    return 0;
}

Go:

package main

import "fmt"
import "strconv"

func main() {
    value, err := strconv.ParseFloat("3px", 64)
    fmt.Printf("%f, %v
", value, err)
    // strconv.ParseFloat: parsing "3px": invalid syntax
}
  • 写回答

2条回答 默认 最新

  • dora12345678 2019-08-31 03:47
    关注

    No, there is no way to convert the longest valid prefix of a string to a float. Value being converted should be valid. From Docs : If s is well-formed and near a valid floating point number, ParseFloat returns the nearest floating point number

    https://golang.org/pkg/strconv/#ParseFloat

    If you consider what C is doing, it is actually changing "3px" --> "3" first internally and then parsing. In Go, you have to explicitly strip out invalid chars before strconv can convert it.

    评论

报告相同问题?

悬赏问题

  • ¥15 蓝桥oj3931,请问我错在哪里
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染