2012-07-26 40 views
2

我目前正在爲我的公司製作支票打印解決方案。打印支票時,您需要從支付的金額中打印出數百萬,數十萬,數千,數千,數百,數十和單位(英鎊/美元/歐元等)。將數字細分爲數千,數百等

在111232.23的情況下,我從下面寫的代碼正確輸出以下內容。我不能幫助感覺有一個更有效或可靠的方法來做到這一點?有沒有人知道這樣做的圖書館/類數學技術?

float(111232.23) 
Array 
(
    [100000] => 1 
    [10000] => 1 
    [1000] => 1 
    [100] => 2 
    [10] => 3 
    [1] => 2 
) 

<?php 

$amounts = array(111232.23,4334.25,123.24,3.99); 

function cheque_format($amount) 
{ 
    var_dump($amount); 
    #no need for millions 
    $levels = array(100000,10000,1000,100,10,1); 
    do{ 
     $current_level = current($levels); 
     $modulo = $amount % $current_level; 
     $results[$current_level] = $div = number_format(floor($amount)/$current_level,0); 
     if($div) 
     { 
      $amount -= $current_level * $div; 
     } 
    }while($modulo && next($levels)); 

print_r($results); 
} 

foreach($amounts as $amount) 
{ 
cheque_format($amount); 
} 
?> 
+0

你知道在php中,你可以簡單地在小數點分隔符處拆分數字,然後從最後一個位置(長度)到第一個(0)循環for循環?雖然我很欽佩你的精神,但我認爲這樣做的數學方式不會更快。 – konqi 2012-07-26 12:18:14

回答

3

我想你只是重新編寫了PHP的number_format函數。我的建議是使用PHP函數而不是重寫它。

<?php 

$number = 1234.56; 

// english notation (default) 
$english_format_number = number_format($number); 
// 1,235 

// French notation 
$nombre_format_francais = number_format($number, 2, ',', ' '); 
// 1 234,56 

$number = 1234.5678; 

// english notation without thousands separator 
$english_format_number = number_format($number, 2, '.', ''); 
// 1234.57 

?> 
+0

我確實需要實際的數字,因爲他們必須放在支票上的特定框 – Leo 2012-07-26 12:38:25

+0

@Leo然後使用PHP函數來回顯數字,但保持原始數據不變。 – Fluffeh 2012-07-26 12:45:47

2

我不知道PHP腳本會正是這一點,但如果你有10000,1000,100,10,1作爲事情你需要的金額。美元多少萬元?

floor($dollar/10000) 

多少萬?

floor(($dollar%10000)/1000) 

1

這不是問題的答案,但下面也打破小數。

function cheque_format($amount, $decimals = true, $decimal_seperator = '.') 
{ 
    var_dump($amount); 

    $levels = array(100000, 10000, 1000, 100, 10, 5, 1); 
    $decimal_levels = array(50, 20, 10, 5, 1); 

    preg_match('/(?:\\' . $decimal_seperator . '(\d+))?(?:[eE]([+-]?\d+))?$/', (string)$amount, $match); 
    $d = isset($match[1]) ? $match[1] : 0; 

    foreach ($levels as $level) 
    { 
     $level = (float)$level; 
     $results[(string)$level] = $div = (int)(floor($amount)/$level); 
     if ($div) $amount -= $level * $div; 
    } 

    if ($decimals) { 
     $amount = $d; 
     foreach ($decimal_levels as $level) 
     { 
      $level = (float)$level; 
      $results[$level < 10 ? '0.0'.(string)$level : '0.'.(string)$level] = $div = (int)(floor($amount)/$level); 
      if ($div) $amount -= $level * $div; 
     } 
    } 

    print_r($results); 
} 
+0

非常不錯。+ 1從我身邊 – 2017-07-20 17:15:00

相關問題