PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] How to check if a number has a decimal place/is a whole number?

 August 09, 2022     decimal, floating-point, java, java-8     No comments   

Issue

My input field BigDecimal num may contain both integer and floating numbers.

num = 45
or 
num = 45.5343434

If the BigDecimal input field num contains decimal places, then I would like to limit the decimal places to 4.

Desired Output : 45.5343 if input num = 45.5343434
Desired Output : 45 if input num=45

How can I do that?


Solution

You are interested in what is called the scale of your BigDecimal.

Call BigDecimal#scale.

BigDecimal x = new BigDecimal( "45.5343434" );
BigDecimal y = new BigDecimal( "45" );

x.scale(): 7

y.scale(): 0

You asked:

I would like to limit the decimal places by 4

Test for the scale being larger than four. If so, round.

    BigDecimal num = new BigDecimal(45);
    if (num.scale() > 4) {
        num = num.setScale(4, RoundingMode.HALF_UP);
    }
    System.out.println(num);

Output:

45

In case of more decimals:

    BigDecimal num = new BigDecimal("45.5343434");

45.5343

You can choose a different rounding mode to fit with your requirements.



Answered By - Ole V.V.
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing