是否有正则表达式来修剪两位小数后的数字?

Posted

技术标签:

【中文标题】是否有正则表达式来修剪两位小数后的数字?【英文标题】:Is there a Regex to trim numbers after two decimal places? 【发布时间】:2021-11-17 06:36:05 【问题描述】:

我正在尝试减少小数位数,出于某种原因,使用“固定小数”258.2 不会将我列中的所有数字更改为两位小数。

在将数字指定为具有 2 位的固定小数后,我几乎有以下内容:

    6.933141 5.13 1.56 2.94 1.54 6.470931

所以改变固定小数的数量对我没有用,所以我一直在尝试使用 RegEx,并想出了(^\d+.\d2)。但是,这仅标识了我想要保留的内容。

有没有办法使用 Regex_Replace 来做到这一点?

提前感谢大家的帮助!

【问题讨论】:

为什么不使用printf 格式%.2f 打印2 位小数? 【参考方案1】:

使用

^(\d+\.\d2)\d+$

替换$1。见regex proof。

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to $1:
--------------------------------------------------------------------------------
    \d+                      digits (0-9) (1 or more times (matching
                             the most amount possible))
--------------------------------------------------------------------------------
    \.                       '.'
--------------------------------------------------------------------------------
    \d2                    digits (0-9) (2 times)
--------------------------------------------------------------------------------
  )                        end of $1
--------------------------------------------------------------------------------
  \d+                      digits (0-9) (1 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

【讨论】:

以上是关于是否有正则表达式来修剪两位小数后的数字?的主要内容,如果未能解决你的问题,请参考以下文章