Is there's any way to format an input[type='number']
value to always show 2 decimal places?
Example: I want to see "0.00"
instead of 0
.
Thanks
Is there's any way to format an input[type='number']
value to always show 2 decimal places?
Example: I want to see "0.00"
instead of 0
.
Thanks
You can't really, but you a halfway step might be:
Solved following the suggestions and adding a piece of jQuery to force the format on integers parseFloat($(this).val()).toFixed(2)
Using the step
attribute will enable it. It not only determines how much it's supposed to cycle, but the allowable numbers, as well. Using step="0.01"
should do the trick but this may depend on how the browser adheres to the standard.
The solutions which use input="number"
step="0.01"
work great for me in Chrome, however do not work in some browsers, specifically Frontmotion Firefox 35 in my case.. which I must support.
My solution was to jQuery with Igor Escobar's jQuery Mask plugin, as follows:
This works well, of course one should check the submitted value afterward :) NOTE, if I did not have to do this for browser compatibility I would use the above answer by @Rich Bradshaw.
Take a look at this:
This is the correct answer:
import { Component, Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'replace' }) export class ReplacePipe implements PipeTransform { transform(value: any): any { value = String(value).toString(); var afterPoint = ''; var plus = ',00'; if (value.length >= 4) { if (value.indexOf('.') > 0) { afterPoint = value.substring(value.indexOf('.'), value.length); var te = afterPoint.substring(0, 3); if (te.length == 2) { te = te + '0'; } } if (value.indexOf('.') > 0) { if (value.indexOf('-') == 0) { value = parseInt(value); if (value == 0) { value = '-' + value + te; value = value.toString(); } else { value = value + te; value = value.toString(); } } else { value = parseInt(value); value = value + te; value = value.toString(); } } else { value = value.toString() + plus; } var lastTwo = value.substring(value.length - 2); var otherNumbers = value.substring(0, value.length - 3); if (otherNumbers != '') lastTwo = ',' + lastTwo; let newValue = otherNumbers.replace(/\B(?=(\d{3})+(?!\d))/g, ".") + lastTwo; parseFloat(newValue); return `${newValue}`; } } }