How to check the precision of Float - java

I have Float like this one:
Float f = Float.valueOf("9.222333999444555666");
System.out.println(f); //prints 9.222334
Is there a way to count the number of digits after the . sign without using regex: f.toString().split("\\.")[1].length()?

Simply convert the value to String and get the place of the decimal point.
String s = "" + f;
int i = s.indexOf(".")
System.out.println("The number of digits after the decimal point are " + s.length()-i-1
EDIT: Read OP's comment and doubt about how to round off a float. That question is answered here: Format Float to n decimal places
For quick reference, use this: String.format("%.2f", f). What you have to understand that Java's Float and Double do not have methods and attributes for manipulating precision after the decimal point. There are several reasons for Java to do this, but all you should remember is to convert Float and Double to String, manipulate them however you want and then convert back.

Related

- Rounding a double up & removing the numbers after a decimal point -

Could someone tell me how I can round a double & then remove the numbers after the decimal places - & then convert this number to a String please?
e.g. start with a double value 55.6666666666667 - round it up to a double value of 56.0000000000 -
or start with 55.333333333333 - round down to a double value of 55.0000000000 -
& then remove the decimal point and trailing zeros - convert to String.
Thanks.
The best way to round a value to the nearest integer is:
int x = (int)Math.round(55.6666666666667);
x will be 56. You can also use Math.ceil() and Math.floor() to round up or down respectively. Finally to make x a string use String.valueOf(). Like this:
String xString = String.valueOf(x);
If you wanted to do it all on one line:
String xString = String.valueOf(Math.round(55.6666666666667));
You can read more about the Math class here and the String class here.
Use the Math.round() function. You can cast it to an int to eliminate the decimal places, or you can use Math.floor() or Math.ceil() to round it down or up before casting.
Assuming that you don't actually want to save the rounded value, but just want to see it as a string, this should do everything you want, where x is the double:
String s = String.format("%.0f", x);

How return only two decimals with float? [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
What's the best practice to round a float to 2 decimals? [duplicate]
(7 answers)
Closed 9 years ago.
I've got a float value and i need to have only two decimals after comma. I'm using this code:
public static float getWhatINeed() {
StatFs statFs = new StatFs(Environment.getDataDirectory().getAbsolutePath());
float total =
((float)statFs.getBlockCount() * statFs.getBlockSize()) / (1073741824);
return total;
}
And it returns for example: 12.552425 in a textview. I need display something like: 12.55 that is enough for me. I saw this:
String s = String.format("%.2f", 1.2975118);
somewhere but I can't use it in my case because I use a float value and I need to use float. How could I solve this?
There is no mechanism to limit the number of decimal points in a float. A float is a float and it has an "unlimited" number of decimals. The String display of a float may be limited to a format only showing a specific number of decimals.
If you really NEED 2 decimals, use BigDecimal
You basically have 4 options:
return a float and deal with the fact that there are n decimal places
format to a String (which means a lot of string parsing if you need to do calculation)
convert to use BigDecimal
convert to use int and assume that the ones digit represents hundredths.
Did you try:
new DecimalFormat("00.00").format(1.2975118);
You can try as follows
DecimalFormat df = new DecimalFormat("0.##");
float a=1.256f;
System.out.println(df.format(a));
}
Out put
1.26
After setting precision and get as a String You can canvert it back to float by
float f = Float.parseFloat(YourString);

Rounding off 2 decimal places in Java for whole number [duplicate]

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 9 years ago.
I have the following and the question is, for example if zzi = 95 then myNum will be correctly displayed as 32.33, exactly as I want it too with two decimal places.
However if zzi = 94, myNum will be displayed as 32.0 instead of 32.00
How to display it as 32.00?
float xFunction(int zzi) {
float myNum = (zzi + 2);
myNum = myNum / 3;
int precision = 100; // keep 4 digits
myNum = (float) (Math.floor(myNum * precision + .5) / precision);
return myNum;
}
Thanks before.
Your question is not so much about rounding a number as it is about rounding a display or String representation of a number. The solution:
Use new DecimalFormat("0.00");
Or String.format("%.2f", myNumber);
Or new java.util.Formatter("%.2f", myNumber);
Or System.out.printf("%.2f", myNumber);
Note: avoid use of float whenever possible, and instead prefer use of double which greatly improves numeric precision at little cost. For financial calculations use neither but instead opt for integer calculations or use BigDecimal.
Remember:
1) printing the number displaying two decimal places is very different from rounding the actual value. In other words "representation" != actual value.
2) floating point values are always imprecise. Even with rounding, you may or may not get an "exact value".
Having said that, the simplest approach is:
float myNum = ((123.456 * 100.0) + .5) / 100.0;
new DecimalFormat("#.##").format(myNum );
You can use DecimalFormat
System.out.println(new DecimalFormat("0.00").format(xFunction(94)));
You should work on the printing function. I assume you are using a System.out.println: replace it with
System.out.format("%.2f", numberToPrint);
Read the docs for that function to discover more about format strings.

How to truncate the double value? [duplicate]

This question already has answers here:
Are there any functions for truncating a double in java?
(11 answers)
Closed 9 years ago.
I want to truncate the double.
e.g.
double d=3.123456789087654;
if I want to truncate It to the 10th digit after the decimal
the result should be
result: 3.1234567890
I don't need round off value as a result
I tried my own function as
static double truncateDouble(double number, int numDigits) {
double result = number;
String arg = "" + number;
int idx = arg.indexOf('.');
if (idx!=-1) {
if (arg.length() > idx+numDigits) {
arg = arg.substring(0,idx+numDigits+1);
result = Double.parseDouble(arg);
}
}
return result ;
}
but didn't get the appropriate result as I want..
can anybody please help me to clear my problem.
Does java supports such any function that supports truncation not round off??
In general, you can't, at least not by using double. The reason is that many numbers simply can't be represented exactly, even if they have a small number of decimal digits.
Take 0.1 as an example. The nearest double is 0.1000000000000000055511151... and no amount of truncation would give you exactly 0.1.
You can use the DecimalFormat class.
double d = 3.123456789087654;
DecimalFormat newFormat = new DecimalFormat("#.##########");
double tenDecimal = Double.valueOf(newFormat.format(d));
this will round the last digit.
I am agree with NPE. no amount of truncation would give you exactly 0.1.
only way is to convert in to string and after substring convert back to double.

Print the number of digits before a decimal point

I know there are ways to get the number of digits after a decimal point, for instance the substring method, but how would I go about doing this for the number of digits before a decimal place?
I need to use this to convert US change (double) into Euro change(double). The way I would like to do this is by taking the number before a decimal (such as $1.) and times it by its euro equivalent (.7498) and take the number after a decimal (.16) and times that by its .01 euro coin value (.0075), add both values together to get the euro equivalent of $1.16 (.8698).
To get the number before decimal point,do this:
String str = new Double(your_double_number).toString().subString(0,str.indexOf('.'));
double v = Double.valueOf(str);
If you are using '$' sign then take 1 in place of 0.
Hope it will help you.
convert US change (double) into Euro change(double)
Please don't do that. Never, never, ever use double or float to represent money, because those datatypes cannot represent most decimal fractions, so you get rounding errors before you even start to do any calculations.
Instead, use BigDecimal.
First of all - just multiplying the Dollar value by the exchange rate will get you the euro value so there's no need to do that as far as i can see - you will just introduce rounding errors.
But if you did need to - just use substring
String dollarVal = "$1.16"
String justFullDollar = dollarVal.substring(1, dollarVal.indexOf("."));
String justCents = dollarVal.substring(dollarVal.indexOf(".")+1);
The Correct way would be to store all you money as integers or arbitrary precision objects that way you get no floating point errors too.
Convert to cents, multiply and convert back again.
e.g.
String dollarVal = "$1.16"
BigDecimal dollars = new BigDecimal(dollarVal.substring(1)); //1.16
BigDecimal cents = dollars.multiply(new BigDecimal(100)); //116
BigDecimal eurocents = cents.multiply(new BigDecimal(exchangeRate)); //86.9768
BigDecimal euros = eurocents.divide(new BigDecimal(100)); //0.869768
DecimalFormat formatter = new DecimalFormat("###.00");
String euroVal = "€" + formatter.format(euros);
You can use
String s[] = new Double(your number).toString().split(".");
The s[0] is the number before decimal point. and s[1] is the number after decimal point.
Both are in String, so you need to parse them into double using
double num1 = Double.parseDouble(s[0]);
double num2 = Double.parseDouble(s[1]);

Categories

Resources