本文介绍了解析一个数字但保留负数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将数字取消格式化为其原始形式,但要保留它是否为负数.堆栈溢出的某个人让我找到了这段代码,该代码工作得非常好,但并没有保留负面信息.
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');更多推荐
解析一个数字但保留负数
发布评论