Get String Zero Decimal Floating Point

advertisements

I have a string string(5) "388.0". I simply want to get exactly float number with one zero or two zero or whatever numbers comes after decimal. How can I achieve it?

Simply (float)$val gives me only float(388) without zero.


Have you tried the built-in number_format function ?

<?php

$nb = '388.0';

var_dump(number_format((float)$nb, 0)); // string '388'
var_dump(number_format((float)$nb, 1)); // string '388.0'
var_dump(number_format((float)$nb, 2)); // string '388.00'

Of course, if you cast your string as a float, then it will by default be (float)388 if the numbers after the decimal point are all 0. I don't think there's a way around that, but (float)388 === 388.0 is true.