skip to Main Content

the input is always showing 4 decimal places. Is there a way to limit it to 2?

I’ve tried doing a math.round at the database, I’ve tried using formatting of f2, it does not seem that anything I try will get the thing to limit to 2 decimal places.

@page "/"
<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
<input type="number"
       step="0.01"
       class="rounded no-spinner p-2 text-right w-full"
       @bind="currentCount" />

@functions {
    decimal currentCount = 0.0001m;

    void IncrementCount()
    {
            currentCount = currentCount + 1.2m;
    }
}

blazorfiddle

2

Answers


  1. According to the test result, we can clearly to see that even if we set limitation for the input with step="0.01", so that I think we could only add validation and format the number when set it.

    void IncrementCount()
    {
         currentCount = Math.Round(currentCount + 1.2m, 2);
    }
    

    We might also try @oninput="HandleInputChange" so that we can moidfy the data when the input would change.

    enter image description here

    Login or Signup to reply.
  2. As I commented before, I suggest the use of get setters.

    My suggested code is as follows:

    private decimal currentCount = 0.0001m;
    
    public decimal CurrentCount
    {
        get => Math.Round(currentCount, 2);
        set => currentCount = value;
    }
    

    And as for the bind you can simply declare the new value @bind="CurrentCount"

    @page "/"
    <h1>Counter</h1>
    
    <p>Current count: @CurrentCount</p>
    
    <button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
    <input type="number"
           step="0.01"
           class="rounded no-spinner p-2 text-right w-full"
           @bind="CurrentCount" />
    
    @functions {
        decimal currentCount = 0.0001m;
    
        public decimal CurrentCount
        {
                get => Math.Round(currentCount, 2);
                set => currentCount = value;
        }
    
        void IncrementCount()
        {
                CurrentCount += 1.2m;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search