Liam Fell
Liam Fell

Reputation: 1320

PHP string to numeric conversion with decimal places

I have a string ($maxDeposit) which is a numeric monetary value. So, for example:

123.00

This string is being passed in to jQuery, it needs to be passed in as a numeric data type. I'm achieving this using the following:

$maxDeposit = floatval($maxDeposit);

This loses the last last decimal place however, so my number looks like:

123.0

I have this method of converting the number to two decimal places:

$maxDeposit =  sprintf('%0.2f', round($maxDeposit, 2));

However this also converts the number back to a string. Is there a way I can convert the string to a float but keep the last decimal place? Thanks

Upvotes: 1

Views: 73

Answers (2)

calraiden
calraiden

Reputation: 1818

I think, You can use floatval/float and number_format.

$maxDeposit = number_format(floatval($maxDeposit), 2);

or

number_format((float)$maxDeposit, 2, '.', '');

http://php.net/manual/pt_BR/function.number-format.php

Upvotes: 1

Alex Blex
Alex Blex

Reputation: 37018

No, float is a numeric value, and 123.00 is its representation with 2 decimal places. It is responsibility of view layer to format numbers. In your case it is jQuery, e.g. console.log(maxDeposit.toFixed(2)).

Upvotes: 2

Related Questions