-1

可能重复: 如何在 JavaScript 中用逗号打印一个数字作为千位分隔符

我正在尝试以这种格式获取值,$1,000,000. 现在我得到了这种格式的值,1000000它工作正常,但我不想要这个。我希望它的价值为 1,000,000 美元,并在我的PHP代码中更改并接受它。

我的HTML

<form action="index.php" method="Get">
    Enter the present value of pet: <input type="text" name="v" value="1000000"/><br>
    Enter the value of the pet you want: <input type="text" name="sv" value="1951153458"/><br>

    <input type="submit" />
</form>

这是我的PHP:

<?php
    $i           = 0;
    $v           = isset($_GET['v']) ? (float) $_GET['v'] : 1000000;
    $sv          = isset($_GET['sv']) ? (float) $_GET['sv'] : 1951153458;
    $petearn     = 0;
    $firstowner  = 0;
    $secondowner = 0;

    And so on..............

我的计算器以这种方式工作正常:

http://ffsng.deewayz.in/index.php?v=1000000&sv=1951153458

但我希望它是:

http://ffsng.deewayz.in/index.php?v=$1,000,000&sv=$1,951,153,458

我很困惑如何将此格式更改$1,000,000为此1000000或是否有其他方式。我需要使用任何 JavaScript 代码吗?在提交表格之前?

有人试图通过以下方式帮助我,但我不知道如何使用它。

function reverse_number_format($num)
{
    $num = (float)str_replace(array(',', '$'), '', $num);
}
4

5 回答 5

4

只需替换字符串中的任何非数字字符:

$filteredValue = preg_replace('/[^0-9]/', '', $value);

更新

$value = '$1,951,1fd53,4.43.34'; // User submitted value

// Replace any non-numerical characters but leave dots
$filteredValue = preg_replace('/[^0-9.]+/', '', $value);

// Retrieve "dollars" and "cents" (if exists) parts
preg_match('/^(?<dollars>.*?)(\.(?<cents>[0-9]+))?$/', $filteredValue, $matches);

// Combine dollars and cents
$resultValue = 0;
if (isset($matches['dollars'])) {
    $resultValue = str_replace('.', '', $matches['dollars']);
    if (isset($matches['cents'])) {
        $resultValue .= '.' . $matches['cents'];
    }
}

echo $resultValue; // Result: 1951153443.34
于 2012-10-26T12:55:45.153 回答
3
$num = preg_replace('/[\$,]/', '', $num);
于 2012-10-26T12:55:12.983 回答
1

要使用您提供的功能来做到这一点:

    $v = 1000000;
if(isset($_GET['v'])){
  $v = reverse_number_format($_GET['v']);
}

在您的 reverse_number_format 函数中添加该行return $num;

于 2012-10-26T12:58:16.727 回答
0

您应该使用 PHP的 floatval函数。

于 2012-10-26T12:54:29.010 回答
0

在服务器上进行计算,就像你已经在做的那样。然后只需使用掩码将其显示给用户。

像:

function formated(nStr) {
    curr = '$ ';
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    if (x1 + x2) {
        return curr + x1 + x2
    }
    else {
        return ''
    }
}

请参阅http://jsfiddle.net/RASG/RXWTM/上的工作示例。

于 2012-10-26T13:01:06.833 回答