-6

How to get the decimal part of floating number as decimal in Java?

Like If float f=2.34;

Then decimal part=34;

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Not only is this question a duplicate, it is unclear what you want. Let's say the input is 0.015: should the result be a String ("015")? Or a number of hundredths, truncated (1)? Or a number of hundredths, rounded up (2)? It's important to be specific so you don't waste the time of everyone involved. – Patrick Parker Dec 31 '16 at 09:48

2 Answers2

1

Try this-

float f=2.34;
float deci = (f - (int)f)*(Math.Pow(10,getDecimalPlaces(f));

getDecimalPlaces(Float f) {
   String txt = Float.toString(f):
   int integerPlaces = txt.indexOf('.'); 
   int decimalPlaces = txt.length() - integerPlaces - 1;
   return decimalPlaces;
}
Rehban Khatri
  • 924
  • 1
  • 7
  • 19
0
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
    public static String getDecimalPart(double number, int numOfDigits){

        return String.format("%."+numOfDigits+"f", number-(int)number);
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        System.out.println(getDecimalPart(2.454,2));
    }
}
Rahul Reddy Vemireddy
  • 1,149
  • 1
  • 10
  • 14