junior_java_develop
junior_java_develop

Reputation: 63

How to remove leading zeros from 'negative' alphanumeric string

Good day everyone.

I have an alphanumeric value. For example: "-00000050.43". And I need to convert it to BigDecimal (prefer, 'cuz it's an amount of $) or Float or Double (depends on the count of digits after '.'. Usually there are two digits) like "-50.43". So, I have 3 different solutions for positive alphanumeric value. Please see them below:

Regex

"00000050.43".replaceFirst("^0+(?!$)", "")

Apache Commons

StringUtils.stripStart("00000050.43","0");

And Google Guava

CharMatcher.is('0').trimLeadingFrom("00000050.43")

It doesn't work for a negative value. Unfortunately, I don't get any idea how to deal with '-' at the start. Thanks, guys! Have a good day.

Upvotes: 1

Views: 305

Answers (2)

Adam Macierzyński
Adam Macierzyński

Reputation: 550

If you want to transform the alphanumeric string value to BigDecimal, you don't need to make any action on this string. BigDecimal has a constructor which takes a string alphanumeric value as an argument.

String val = "-0000054.1";
BigDecimal bd = new BigDecimal(val);

Upvotes: 8

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626932

You can use

"00000050.43".replaceFirst("^(-?)0+(?!$)", "$1")

The ^(-?)0+(?!$) pattern will match

  • ^ - start of string
  • (-?) - Group 1 ($1 in the replacement pattern will refer to this group value, if there is a - matched, it will be restored in the resulting string): an optional -
  • 0+ - one or more zeros
  • (?!$) - no end of string position immediately on the right allowed.

See this regex demo.

Upvotes: 2

Related Questions