I’m trying to properly format numbers that are being displayed in an edit template. As an example, in MySQL the field is defined as DECIMAL(4,2). The saved value is 9.20.
In the view template, I have:
$this->Number->format($race->dial, [‘places’ => 2])
which correctly displays 9.20
However, in the edit template, I have:
$this->Form->control(‘dial’);
which incorrectly displays 9.2
I have tried adding a number of options to the control to properly mask the field but none seem to work. Whether is it 2 or 3 decimal points, I need to make sure it displays the trailing zeros.
I feel like I’m missing something real simple here but I’m struggling. Any suggestions on how to display all decimal places?
Usually instead of messing around with a frameworks “formatting” I just use php like
$namt = number_format($amt, 2, '.', '');
And done. I use cake, laravel, and yii2, and a custom framework, and found it best to stray away from too much framework biased code. The “guts” of these frameworks is regular php code anyway.
You are correct and I know number_format() will give the formatting I’m looking for (there is some nice JS code that would work too). What I’m struggling with is my inexperience with how to incorporate that into the View code. In my edit.ctp template, I display the value from the database which is supposed to be 9.20 but it shows as 9.2. Using the framework code:
It doesn’t matter how you format the value in the form field, the browser is going to get rid of all the extra trailing zeroes. The solution is 100% JavaScript. You can see this for yourself if you put something like 'value' => '100.100000' in the options array in your control call. The browser will render it as just “100.1”.
Gave your answers some more thought and I agree that controlling how a float is presented is a challenge. Also, I like JS but if I can do it “natively”, I want to give it a shot. With that, I attacked this from a different angle. Using the same code example I presented earlier, this is what I did:
In this application, rounding is not an issue. There are a series of decimal numbers that have either 2 or 3 positions to the right of the decimal point but they have to be 0 padded to fill all 2 or 3 positions. It looks like the solution is working properly.
With a generic text field, people will be able to enter letters and punctuation and the like into it, which should be prevented by the browser if it knows it’s a number field. Also, you won’t get the (dubious) functionality of being able to “scroll” the number. If you’re okay with all of that, then this is probably fine.