我在考虑一个“数字近似”函数,它接受一个整数并返回一个字符串,类似于以下内容:
45 => "some"
100 => "1 hundred"
150 => "over 1 hundred"
1,386 => "over 1 thousand"
15,235,742 => "over 15 million"
797,356,264,255 => "over 700 billion"
我希望将它用于,例如,以近似的方式说出数据库表中有多少行。
我无法想象如何描述这样的事情,所以寻找它有点棘手。
是否有任何机构知道这样做的现有功能(最好是PHP),或者任何人都可以描述/指向算法让我开始自己动手?
答案 0 :(得分:1)
看一下这个包:http://pear.php.net/package-info.php?package=Numbers_Words
评论中解释的以下代码将会这样做
我有两种选择。一个只有言语。第二个是你在答案中准确说的那个。第一个更容易,因为您不需要再将单词预转换为数字。
<?php
require_once "Numbers/Words.php";
$number = new Numbers_Words();
$input = "797,356,264,255";
$input = str_replace(',', '',$input); // removing the comas
$output = $input[0]; // take first char (7)
$output2 = $input[0].'00'; //7 + appended 00 = 700 (for displaying 700 instead of 'seven hundred')
for ($i = 1; $i<strlen($input); $i++) {
$output .= '0';
}
$words = $number->toWords($output); //seven hundred billion
$output3 = explode(' ', $words);
$word = $output3[count($output3)-1]; // billion
echo "Over ". $words; // Over seven hundred billion
#####################
echo "Over " . $output2 . ' ' . $word; // Over 700 billion
答案 1 :(得分:0)
你想做什么是如此主观。这就是你无法找到任何功能的原因。
对于您的算法,您可以定义一些与模式匹配的字符串。例如:over ** million
匹配8位数字。您可以找到第一个2位数字并替换字符串中的**
。
答案 2 :(得分:0)
经过一番摆弄后,我想出了这个:
function numberEstimate($number) {
// Check for some special cases.
if ($number < 1) {
return "zero";
} else if ($number< 1000) {
return "less than 1 thousand";
}
// Define the string suffixes.
$sz = array("thousand", "million", "billion", "trillion", "gazillion");
// Calculate.
$factor = floor((strlen($number) - 1) / 3);
$number = floor(($number / pow(1000, $factor)));
$number = floor(($number / pow(10, strlen($number) - 1))) * pow(10, strlen($number) - 1);
return "over ".$number." ".@$sz[$factor - 1];
}
输出如下内容:
0 => "zero"
1 => "less than 1 thousand"
10 => "less than 1 thousand"
11 => "less than 1 thousand"
56 => "less than 1 thousand"
99 => "less than 1 thousand"
100 => "less than 1 thousand"
101 => "less than 1 thousand"
465 => "less than 1 thousand"
890 => "less than 1 thousand"
999 => "less than 1 thousand"
1,000 => "over 1 thousand"
1,001 => "over 1 thousand"
1,956 => "over 1 thousand"
56,123 => "over 50 thousand"
99,213 => "over 90 thousand"
168,000 => "over 100 thousand"
796,274 => "over 700 thousand"
999,999 => "over 900 thousand"
1,000,000 => "over 1 million"
1,000,001 => "over 1 million"
5,683,886 => "over 5 million"
56,973,083 => "over 50 million"
964,289,851 => "over 900 million"
769,767,890,753 => "over 700 billion"
7,687,647,652,973,863 => "over 7 gazillion"
它可能不是最漂亮的解决方案,也可能是最优雅的解决方案,但似乎工作并且做得很好所以我可能会继续这样做。
我感谢大家的指示和建议!