英文:
Best way to convert string of digits into its numerical big.Rat value
问题
我正在使用math/big
库进行工作。
我想知道是否有一种简便的方法将像"2023930943509509"
这样的数字字符串转换为big.Rat
类型的值。
我知道可以使用.SetString()
方法将字符串转换为big.Int
类型的值,但是对于Rat
类型是否也可以这样做呢?
英文:
I'm working with math/big
.
I was wondering if somebody knows a short way to convert a string
of digits like "2023930943509509"
to a big.Rat
type value.
I know .SetString()
can be used for big.Int
types, but can the same be done for the Rat
type?
答案1
得分: 3
你不需要死记硬背这些方法和函数,每当你查找某个内容时,可以查看包的文档。你可以在这里找到相关包的文档:math/big
。
从文档中可以看到,big.Rat
类型也有一个 Rat.SetString()
方法,你可以用它来实现这个目的:
> func (z *Rat) SetString(s string) (*Rat, bool)
> SetString 将 z 设置为 s 的值,并返回 z 和一个表示成功与否的布尔值。s 可以是分数形式的字符串 "a/b",也可以是浮点数,可选地后面跟着一个指数。整个字符串(而不仅仅是前缀)必须是有效的才能成功。如果操作失败,z 的值是未定义的,但返回值是 nil。
以下是使用示例:
r := big.NewRat(1, 1)
if _, ok := r.SetString("2023930943509509"); !ok {
fmt.Println("解析字符串失败!")
}
fmt.Println(r)
fmt.Println(r.FloatString(2))
输出结果(在 Go Playground 上尝试):
2023930943509509/1
2023930943509509.00
英文:
You don't have to learn these methods and functions by heart, whenever you look for something, check the package documentation. The doc of the package in question can be found here: math/big
.
As you can see in the doc, there is a Rat.SetString()
method for the big.Rat
type too which you can use for this purpose:
> 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.
Example using it:
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))
Output (try it on the Go Playground):
2023930943509509/1
2023930943509509.00
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论