2 Replies - 295 Views - Last Post: 20 January 2013 - 06:18 PM Rate Topic: -----

#1 Eggy  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 31
  • Joined: 15-November 12

How to display the amount of digits in a number?

Posted 20 January 2013 - 02:47 PM

Ok, say I have

y = 101.333; 


How can I display how many digits there are before (3 in this case) and after the decimal point (3 in this case)?

Can we possibly use the DecimalFormat class to do this?

If so, how please?

Thank you.

This post has been edited by Eggy: 20 January 2013 - 02:55 PM

Is This A Good Question/Topic? 0
  • +

Replies To: How to display the amount of digits in a number?

#2 Ryano121  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1362
  • Posts: 3,002
  • Joined: 30-January 11

Re: How to display the amount of digits in a number?

Posted 20 January 2013 - 02:52 PM

If it's a double variable -

int digits = Double.toString(y).length;

Same works for Integer, Long, Float etc


Edit - scrap that didn't notice you wanted before and after decimal point.

You could use the split method though.

String[] parts = Double.toString(y).split("\\.");
int before = parts[0].length;
int after = parts[1].length


You should however do a check to see if there is a decimal point in the number to avoid an exception being thrown.

This post has been edited by Ryano121: 20 January 2013 - 02:55 PM

Was This Post Helpful? 3
  • +
  • -

#3 ianian112  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 119
  • View blog
  • Posts: 378
  • Joined: 28-November 09

Re: How to display the amount of digits in a number?

Posted 20 January 2013 - 06:18 PM

Ryan's way works but is definitely not the best.
new BigDecimal(String.valueOf(y)).precision()
is probably the easiest way I know.

This post has been edited by ianian112: 20 January 2013 - 06:21 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1