good_evening
good_evening

Reputation: 21749

How do I format numbers to have only two decimal places?

I want that real numbers would be for example 12.92, but not 12.9241. Is it possible to do like that?

Upvotes: 13

Views: 34891

Answers (4)

Bill Stephen
Bill Stephen

Reputation: 99

$number = 1234.5678;
$teX = explode('.', $number);

if(isset($teX[1])){
    $de = substr($teX[1], 0, 2);
    $final = $teX[0].'.'.$de;
    $final = (float) $final;
}else{
    $final = $number;   
}

final will be 1234.56

Upvotes: 3

John Feminella
John Feminella

Reputation: 311536

In PHP, try number_format:

$n = 1234.5678;

// Two decimal places, using '.' for the decimal separator
// and ',' for the thousands separator.
$formatted = number_format($n, 2, '.', ',');
// 1,234.57

Upvotes: 23

Patrick
Patrick

Reputation: 15717

You can multiply your number by 100, do a rounding of the result and then divide back by 100.

Or in php use the round function round function

$result=round(12.9241, 2);

Upvotes: -1

Clash
Clash

Reputation: 5025

For PHP you can use number_format(), for MySQL use the FORMAT() function.

MySQL: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_format

FORMAT(number, 2)

Example:

mysql> SELECT FORMAT(12332.123456, 4);
       -> '12,332.1235

PHP: http://php.net/manual/en/function.number-format.php

$number = 1234.5678;
$formatted_number = number_format($number, 2, '.', '');
// 1234.56

Upvotes: 4

Related Questions