将数字串转换为其数字 big.Rat 值的最佳方法
Best way to convert string of digits into its numerical big.Rat value
我正在与 math/big
合作。
我想知道是否有人知道将 string
数字(如 "2023930943509509"
)转换为 big.Rat
类型值的简便方法。
我知道 .SetString()
可以用于 big.Int
类型,但同样可以用于 Rat
类型吗?
这些方法和函数不用死记硬背,找东西的时候查一下包文档。相关包的文档可以在这里找到:math/big
.
如您在文档中所见,还有一个 Rat.SetString()
method for the big.Rat
类型也可用于此目的:
func (z *Rat) SetString(s string) (*Rat, bool)
SetString sets z to the value of s and returns z and a boolean indicating success. s can be given as a fraction "a/b" or as a floating-point number optionally followed by an exponent. The entire string (not just a prefix) must be valid for success. If the operation failed, the value of z is un- defined but the returned value is nil.
使用示例:
r := big.NewRat(1, 1)
if _, ok := r.SetString("2023930943509509"); !ok {
fmt.Println("Failed to parse the string!")
}
fmt.Println(r)
fmt.Println(r.FloatString(2))
输出(在 Go Playground 上尝试):
2023930943509509/1
2023930943509509.00
我正在与 math/big
合作。
我想知道是否有人知道将 string
数字(如 "2023930943509509"
)转换为 big.Rat
类型值的简便方法。
我知道 .SetString()
可以用于 big.Int
类型,但同样可以用于 Rat
类型吗?
这些方法和函数不用死记硬背,找东西的时候查一下包文档。相关包的文档可以在这里找到:math/big
.
如您在文档中所见,还有一个 Rat.SetString()
method for the big.Rat
类型也可用于此目的:
func (z *Rat) SetString(s string) (*Rat, bool)
SetString sets z to the value of s and returns z and a boolean indicating success. s can be given as a fraction "a/b" or as a floating-point number optionally followed by an exponent. The entire string (not just a prefix) must be valid for success. If the operation failed, the value of z is un- defined but the returned value is nil.
使用示例:
r := big.NewRat(1, 1)
if _, ok := r.SetString("2023930943509509"); !ok {
fmt.Println("Failed to parse the string!")
}
fmt.Println(r)
fmt.Println(r.FloatString(2))
输出(在 Go Playground 上尝试):
2023930943509509/1
2023930943509509.00