英文:
Formatting a number as currency with a hyphen
问题
我有一个类似这样的字符串:
<?php $string = "1000 - 2000"; ?>
我知道如果它是一个单一的数字,我可以这样格式化它:
<?php
$val = 1000;
echo sprintf("£%u", $val);
?>
这将输出"£1000",但我不确定如何处理由连字符分隔的两个数字。所需的结果应该是"£1000 - £2000"。
英文:
I have a string that looks like this:
<?php $string = "1000 - 2000"; ?>
I know if it were a single number I could format it like this:
<?php
$val = 1000;
echo sprintf("£%u", $val);
?>
Which would output "£1000" but I am unsure how to handle the two numbers separated by a hyphen. The needed result would be "£1000 - £2000"
答案1
得分: 4
你可以通过使用连字符作为分隔符来拆分字符串变量,然后对数组中的每个值进行格式化,然后作为示例,我将格式化后的价格添加到格式化后的价格数组中。
$string = "1000 - 2000";
$values = explode(' - ', $string);
$prices = [];
foreach ($values as $value) {
$price = sprintf("¥%u", $value);
echo $price;
$prices[] = $price;
}
英文:
You can create an array of values by splitting the string variable with hyphens as the delimiter, then for each value in the array format it, then as an example I added the formatted price to the array of formatted prices.
$string = "1000 - 2000";
$values = explode(' - ', $string);
$prices = [];
foreach ($values as $value) {
$price = sprintf("£%u", $value);
echo $price;
$prices[] = $price;
}
答案2
得分: 0
上面的回答是正确的。但我更喜欢不使用 sprintf()
。相反,我将简单地连接货币标识符。
$string = "1000 - 2000";
$currencyIdentifier = "£";
$values = explode(' - ', $string);
$prices = [];
foreach ($values as $value) {
$price = $currencyIdentifier . $value;
echo $price.'<br/>';
$prices[] = $price;
}
print_r($prices);
$newPrice = implode(' - ', $prices);
echo '<br/>' . $newPrice;
这将为您提供所期望的输出:"£1000 - £2000"。
英文:
Above answer is Correct. But I would prefer not to use sprintf()
. Instead I'll simply concatenate the currency identifier.
$string = "1000 - 2000";
$currencyIdentifier = "£";
$values = explode(' - ', $string);
$prices = [];
foreach ($values as $value) {
$price = $currencyIdentifier.$value;
echo $price.'<br/>';
$prices[] = $price;
}
print_r($prices);
$newPrice = implode(' - ', $prices);
echo '<br/>'.$newPrice;
This will give you the desired output "£1000 - £2000"
答案3
得分: -2
首先,您必须查看您是否可以从您获取这两个数字的任何地方分别获取它们。这将是首选解决方案。但是,如果这是不可能的,您可以从字符串中提取它们,然后使用它们创建新的字符串。
在这种情况下,我会使用 sscanf() 函数:
$string = "1000 - 2000";
sscanf($string, '%d - %d', $price1, $price2);
echo "£$price1 - £$price2";
查看演示:https://3v4l.org/Va3Un
英文:
First of all you have to look whether you can get the two numbers separately from wherever you're getting them. That would be the preferred solution. However if this is impossible you can extract them from the string, and use them to create your new string.
I would use sscanf() in this case:
$string = "1000 - 2000";
sscanf($string, '%d - %d', $price1, $price2);
echo "£$price1 - £$price2";
See live demo: https://3v4l.org/Va3Un
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论