HTML5 Number Input - Always show 2 decimal places

匿名 (未验证) 提交于 2019-12-03 02:46:02

问题:

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

回答1:

You can't really, but you a halfway step might be:



回答2:

Solved following the suggestions and adding a piece of jQuery to force the format on integers parseFloat($(this).val()).toFixed(2)



回答3:

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.



回答4:

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.



回答5:

Take a look at this:

 


回答6:

This is the correct answer:



回答7:

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}`;         } } } 


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!