簡體   English   中英

字符串數近似

[英]String number approximation

我在考慮一個“整數近似”函數,該函數需要一個整數並返回一個字符串,類似於以下內容:

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中),或者有人可以描述/指向一種算法來讓我開始滾動自己的算法嗎?

看一下這個包: 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

你想做什么是很主觀的。 這就是為什么您找不到任何函數來執行此操作的原因。

對於您的算法,您可以定義一些與模式匹配的字符串。 例如: over ** million匹配項,包含8位數字。 您可以找到前2位數字,並在字符串中替換**

然后,您可以使用roundfloorceil類的數學函數(取決於您的需要),並找到與您的模式相對應的字符串。

經過一番擺弄之后,我想到了這個:

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"

它可能不是最漂亮的解決方案,也不是最優雅的解決方案,但是它似乎可以工作並且做得很好,所以我可能會同意。

我感謝大家的指導和建議!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM