您可以「輕鬆」轉換包含逗號和點的字符串,但特別是如果您要支持錯位的千位分隔符或允許用戶輸入三位小數時出現含糊不清的情況。
這是您可以使用的盡力而爲的方法。我對任何被誤解的數字不負任何責任!
function stringToNumber($str) {
$last_comma = strrpos($str, ',');
$last_dot = strrpos($str, '.');
if($last_comma === false && $last_dot === false) {
return $str;
} elseif($last_comma !== false && $last_dot !== false) {
if($last_comma < $last_dot) {
// dot is further to the right
return str_replace(',', '', $str);
} else {
// comma is further to the right
return str_replace(',', '.', str_replace('.', '', $str));
}
} elseif ($last_dot !== false) {
// No commas. For thousand-separator the following must hold
if(preg_match('/^[0-9]{1,3}(\\.[0-9]{3})+$/', $str)) {
// every dot is followed by three digits... lets assume the user wanted them as thousand-separators
// For a single dot this assumption may be invalid, but we expect the user to use . as thousand-separator...
return str_replace('.', '', $str);
} else {
// We could check here how many dots are used.
return $str;
}
} else {
// No dots. For thousand-separator the following must hold
if(preg_match('/^[0-9]{1,3}(,[0-9]{3})+,[0-9]{3}$/', $str)) {
// every comma is followed by three digits and there are at least two of them
return str_replace(',', '', $str);
} else {
// So this is it. Single comma. We could check if the comma is followed by three digits, but it still could be legitimate and while we want to support unexpected input we do not want to interfere with valid input like "1,234" meant as 1.234
return str_replace(',', '.', $str);
}
}
}
例子:
function formated_test($str) {
$num = stringToNumber($str);
printf("% 14s => % 14s\n", $str, $num);
}
formated_test("42");
formated_test("42.1");
formated_test("42,1");
formated_test("42.123");
formated_test("42,123");
formated_test("42.123,42");
formated_test("42,123.42");
formated_test("42.123.456");
formated_test("42,123,456");
formated_test("42.123.456,12");
formated_test("42,123,456.12");
輸出:
42 => 42
42.1 => 42.1
42,1 => 42.1
42.123 => 42123
42,123 => 42.123
42.123,42 => 42123.42
42,123.42 => 42123.42
42.123.456 => 42123456
42,123,456 => 42123456
42.123.456,12 => 42123456.12
42,123,456.12 => 42123456.12
看一看* PHP正則表達式* – pbaldauf 2014-11-02 15:14:33
如果你正打算節省的數字是有你不是將它們保存爲兩個不同整數的原因? – JammyDodger231 2014-11-02 15:15:27
如果用戶用小圓點寫小數點,那麼您有一個模糊的值。你如何區分這些價值?編輯你的問題,並提供一些例子,你想他們轉換成什麼。 – 2014-11-02 15:15:53