【问题标题】:how to remove dot from string in lua如何从lua中的字符串中删除点
【发布时间】:2018-11-13 09:43:41
【问题描述】:

我想从字符串中删除点。 例如

242.701000393 = 242701000393

我试过下面的代码,在某些情况下可以正常工作。

string.gsub("242.701000393", "%.", "")

同样,我已经为100999212.707000393 尝试了上述函数。但它不起作用。

我是 lua 的新手。我想在每种情况下都从字符串中删除 .(dot)。

分享你的想法,因为我不知道如何实现它。

按照我的逻辑如下所示

  1. 按点分割字符串并转换成数组
  2. 连接所有数组元素

如果可能,分享它的解决方案。

提前致谢。

代码:

local destination_number =100999212.707000393
destination_number = string.gsub(destination_number, "%.", "")
print(destination_number)

输出:100999212707

预期输出:100999212707000393

【问题讨论】:

  • 100999212.707000393 的输出是什么?您是否将string.gsub() 作为print 函数的参数传递?
  • 我刚刚添加了代码和输出。
  • 数字(可能是双精度)不是字符串。在大多数编程语言中不能删除点
  • 你应该用引号 " 包裹 100999212.707000393,现在 type(destination_number) 是数字而不是字符串。

标签: lua


【解决方案1】:

问题在于数字的准确性 - 浮点舍入,而不是 gsub 的功能。

local destination_number =100999212.707000393
print(destination_number, type(destination_number) )
destination_number = string.gsub(destination_number, "%.", "")
print(destination_number,type(destination_number))

输出

100999212.707   number
100999212707    string

相比...

local destination_number = "100999212.707000393"
print(destination_number, type(destination_number) )
destination_number = string.gsub(destination_number, "%.", "")
print(destination_number,type(destination_number))

输出

100999212.707000393     string
100999212707000393      string

浮点双精度大约有 15 位精度,这意味着 393 在生成数字时会丢失。转成字符串的时候就已经消失了。

15 位数字相当准确,通常足以满足大多数用途,但如果对您来说不够用,则需要考虑替代数据表示。

【讨论】:

  • 谢谢大佬,解释清楚。我暂时不能投票。稍后会投票。
猜你喜欢
  • 1970-01-01
  • 2012-05-14
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
  • 2021-06-13
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
相关资源
最近更新 更多