Search code examples
javaregexcurrencyrounding-error

How to extract the unit and subunit parts from the given amount of money represented in microunits?


I'm working on project in Java and have a price in micro-units.

A price in micro-units is a price, where 1,000,000 micro-units equal one unit of the currency. For example, if price is "€7.99", price_amount_micros is "7990000"

I need to extract 7 and 99 as separate strings. Having read some posts about rounding errors, I think the right way to achieve what I need is to convert the given amount to a string and extract the unit and subunit parts using the following regex:

^(\d+)(\d{2})0000$

However, for some reason, I feel like it's not an elegant way.


Solution

  • You can refine it to:

    ^(\d+)(\d{2})0{4}$
    

    But then you are done imho.

    I handle all Prices as INT in my Databases. 7.99 would be 799 there. There are no Rounding-Errors.