Tôi biết rằng đây là một câu hỏi cũ, nhưng nó vẫn thực tế :).
Làm thế nào về chức năng này?
function numberFormatPrecision($number, $precision = 2, $separator = '.')
{
$numberParts = explode($separator, $number);
$response = $numberParts[0];
if(count($numberParts)>1){
$response .= $separator;
$response .= substr($numberParts[1], 0, $precision);
}
return $response;
}
Cách sử dụng:
// numbers test
numberFormatPrecision(19, 2, '.'); // expected 19 return 19
numberFormatPrecision(19.1, 2, '.'); //expected 19.1 return 19.1
numberFormatPrecision(19.123456, 2, '.'); //expected 19.12 return 19.12
// negative numbers test
numberFormatPrecision(-19, 2, '.'); // expected -19 return -19
numberFormatPrecision(-19.1, 2, '.'); //expected -19.1 return -19.1
numberFormatPrecision(-19.123456, 2, '.'); //expected -19.12 return -19.12
// precision test
numberFormatPrecision(-19.123456, 4, '.'); //expected -19.1234 return -19.1234
// separator test
numberFormatPrecision('-19,123456', 3, ','); //expected -19,123 return -19,123 -- comma separator
Hãy thử điều này với số này: 0,29 và không thành công! – Arsham
làm điều này: $ finalCommishParts = explode ('.', $ Hoa hồng); $ commisshSuffix = (isset ($ finalCommishParts [1])? Substr ($ finalCommishParts [1], 0,2): '00'); $ finalCommish = $ finalCommishParts [0]. '.'. $ CommisshSuffix; –
@AsafMaoz: hãy cẩn thận với sự khác biệt giữa dấu phân cách thập phân với ngôn ngữ. – Wrikken