解析一个数字但保留负数

编程入门 行业动态 更新时间:2024-10-21 11:44:13
本文介绍了解析一个数字但保留负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将数字取消格式化为其原始形式,但要保留它是否为负数.堆栈溢出的某个人让我找到了这段代码,该代码工作得非常好,但并没有保留负面信息.

I am trying to un-format a number to it's original form but keep whether or not it is negative. Someone on stack overflow led me to this code that work's very nicely but it does not keep the negative.

谁能帮我更好地解决这个问题?

Could anyone help me get a better fix on this?

编辑 - 对于美元货币/普通数字

EDIT - For USD Currency/normal numbers

示例:

1,234 = 1234

1,234 = 1234

-1,234 = -1234

-1,234 = -1234

1,234.00 = 1234

1,234.00 = 1234

1,234.56 = 1234.56

1,234.56 = 1234.56

function numberUnformat($number) { $cleanString = preg_replace('/([^0-9\.,])/i', '', $number); $onlyNumbersString = preg_replace('/([^0-9])/i', '', $number); $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1; $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased); $removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot); return (float) str_replace(',', '.', $removedThousendSeparator); }

推荐答案

如果您有可用的 ICU 扩展(在 PHP 5.3 中捆绑),请尝试以下操作:

In case you have the ICU extension (which is bundled in PHP 5.3) available, try this:

$formatter = new NumberFormatter('en_US', NumberFormatter::DECIMAL); echo $formatter->parse('-1,234.56');

更多推荐

解析一个数字但保留负数

本文发布于:2023-11-30 20:54:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:负数   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!