Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert output of number_format back to numbers in PHP?

Tags:

php

PHP can't recognize 1,200.00(generated by number_format) but only 1200.00,

What's the general solution for this problem?

like image 527
user198729 Avatar asked May 29 '10 17:05

user198729


People also ask

Does number format return a string?

Basic number formatting In its most basic form, number_format() accepts a number to format, and returns a string containing the formatted number, rounded to the nearest whole number, with commas between each group of thousands: $myNumber = 1234567.89; // Displays "1,234,568" echo number_format( $myNumber );

How can I get one decimal place in PHP?

$one_decimal_place = number_format(2.10, 1);


2 Answers

You could remove any character that is not a digit or a decimal point and parse that with floatval:

$number = 1200.00; $parsed = floatval(preg_replace('/[^\d.]/', '', number_format($number))); var_dump($number === $parsed);  // bool(true) 

And if the number has not . as decimal point:

function parse_number($number, $dec_point=null) {     if (empty($dec_point)) {         $locale = localeconv();         $dec_point = $locale['decimal_point'];     }     return floatval(str_replace($dec_point, '.', preg_replace('/[^\d'.preg_quote($dec_point).']/', '', $number))); } 
like image 88
Gumbo Avatar answered Sep 24 '22 23:09

Gumbo


If you're using 5.3 or higher (thanks ircmaxell), use numfmt_parse.

like image 45
Donnie Avatar answered Sep 23 '22 23:09

Donnie