DEV Community

Cover image for Input field type "Currency" problem solved πŸ’²πŸ’‘
TechWorld with Nana
TechWorld with Nana

Posted on

11 2

Input field type "Currency" problem solved πŸ’²πŸ’‘

Just recently we implemented a calculator for property yield. So in our calculator, there were some currency input fields, obviously, where user can enter purchase price etc. And these input fields needed to be formatted in German, since most of our users are German.

The problem

The annoying problem we had was, how to display the formatted number while also using it to calculate some other values, because <input type=β€œnumber” /> doesn’t allow displaying German format - 1.000,00.

UI example below:
UI Currency

Side note: we use React-Intl to format the number into a language-specific currency.

Solution

After trying out several options, we came up with the following simple solution:

We use the <input type=number” /> when input field is in focus and save the value in state as a number to use it in calculations. When the input field loses focus (onBlur callback), we switch the Input field to <input type=β€œtext” /> to display the formatted number currency.

Code snippet below:
input field currency react

This way, in order to display and calculate the same value, we don’t have to transform it from number to string and vice versa. Also this requires minimal code change.


You can follow me on Twitter and YouTube.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay