$numval = 12345.50;
數千個分隔符與money_format?
所需的輸出:
12 345,50
逗號,而不是一個點是沒有問題的,但我怎麼能得到千位分隔符是一個空白?我發現PHP money format with spaces但這不是重複的帖子。使用number_format
無疑是個問題,因爲它會舍入輸入值。我不能讓通過它的值完全舍入。
有沒有一個內置的方法來做number_format()
確實做了什麼,但沒有舍入值或我必須寫我自己的功能來做到這一點?
$numval = 12345.50;
數千個分隔符與money_format?
所需的輸出:
12 345,50
逗號,而不是一個點是沒有問題的,但我怎麼能得到千位分隔符是一個空白?我發現PHP money format with spaces但這不是重複的帖子。使用number_format
無疑是個問題,因爲它會舍入輸入值。我不能讓通過它的值完全舍入。
有沒有一個內置的方法來做number_format()
確實做了什麼,但沒有舍入值或我必須寫我自己的功能來做到這一點?
如果四捨五入是出問題,浮點值也是如此。如果你不想四捨五入,你必須返回整數,因爲浮點算法不準確。在這種情況下,你必須自己實現格式化功能。
這是特別是如果您正在處理金錢,則爲true。請參閱Why not use Double or Float to represent currency?
不完全是我問的,但包含了非常重要的一點,我必須接受這一點。永遠不要使用浮動或雙打再次處理金錢。決不。謝謝。 – budwiser
這看起來像函數的版本要使用:
string number_format (float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',')
因此,例如:
$newNumber = number_format($oldNumber, 2, ",", " ");
欲瞭解更多信息,請查閱http://php.net/manual/en/function.number-format.php
從number_format()頁面的this comment(我修改了函數以匹配number_format默認值,儘管)。
爲了防止取整:
function fnumber_format($number, $decimals=0, $dec_point='.', $thousands_sep=',') {
if (($number * pow(10 , $decimals + 1) % 10) == 5) //if next not significant digit is 5
$number -= pow(10 , -($decimals+1));
return number_format($number, $decimals, $dec_point, $thousands_sep);
}
+1實際回答問題^^ – hakre
但是這也行不通。浮動值本質上是四捨五入的。 –
只是一個側面說明 - 我傾向於對number_format()的所有情況瘦肉(包括格式化的錢),因爲[money_format()](http://php.net /manual/en/function.money-format.php)取決於strfmon,並非所有的操作系統都有*咳嗽*窗口! *咳嗽*所以使用它的代碼可能無法在所有服務器上運行。 –