help regarding rounding off numbers - java

float per = (num / (float)totbrwdbksint) * 100;
i m getting the value of per as say 29.475342 . i want it to round off upto two decimal places only.like 29.48 .how to achieve this?

You should do this as part of the formatting - the floating point number itself doesn't have any concept of "two decimal places".
For example, you can use a DecimalFormat with a pattern of "#0.00":
import java.text.*;
public class Test
{
public static void main(String[] args)
{
float y = 12.34567f;
NumberFormat formatter = new DecimalFormat("#0.00");
System.out.println(formatter.format(y));
}
}

As Jon implies, format for display. The most succinct way to do this is probably using the String class.
float f = 70.9999999f;
String toTwoDecPlaces = String.format("%.2f", f);
This will result in the string "71.00"

If you need to control how rounding is done you should check BigDecimal ist has several rounding modes. http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigDecimal.html

You need to be careful here, this answer is not related to java, it relates to all aspects of decimals in many programming languages hence it is generic. The danger lies with rounding numbers, is this, and it has happened in my experience and know that it can be tricky to deal with:
Supposing you are dealing with prices on items, the pricing you get from a retail supplier may be different to the price the computer tells you, sure it is marginally small, but it could add up to big money.
Adding a sales tax on a price can either be positive or negative, it can impact the operating margin of the profit/loss balance sheets...
If you are in this kind of arena of development, then my advice is not to adjust by rounding up/down...it may not show up on small sales of the items, but it could show up elsewhere...an accountant would spot it...Best thing to do is to simply, truncate it,
e.g. 29.475342 -> 29.47 and leave it at that, why?, the .005 can add up to big profit/loss.
In conjunction to what is discussed here...electronic tills and registers use their own variety of handling this scenario, instead of dealing with XX.XXXXXXXXXX (like computers, which has 27/28 decimal places), it deals with XX.XX.
Its something to keep in mind...
Hope this helps,
Best regards,
Tom.

you can use the formatted print method System.out.printf to do the formatted printing if that's what you need

Related

How can I avoid all the if-Statements/Switches in this case? [duplicate]

This question already has answers here:
How to avoid a lot of if else conditions
(8 answers)
Closed 5 years ago.
I am writing a little program which converts all kind of units into other ones. I have the gui and the program working fine but I feel like there is a better way to do it since I have a lot of if statements and switches. For example if the user wants to convert from one currency to another, he choses both currencies with a dropbox. Lets call them fromCurrency and toCurrency. solution will be the result at the end and amount is the amount of money which should be converted. The code for the calculation looks like this:
double convertIt(String fromCurrency, String toCurrency, double amount, double solution)
switch (fromCurrency) {
case "Euro":
if(toCurrency == "US-Dollar"){
solution = amount*(1.2407);
}
if(toCurrency == "Canadian Dollar"){
solution = amount*(1.5492);
}
// ...
// ... checking all possible currencies in which you could convert, then next case
I know this might be pretty basic for most of you but I am really working alot on learning java for a while now and want to understand how to solve problems efficient and elegant. Because of that I would apprecciate any kind of hints on how to solve this problem more efficient since it doesnt feel that way, or at least it doesnt feel elegant. For example 10 currencies would mean 10 switches with 9 if statements each and there will probably be more
Use a table-like structure.
Use a structure like Guava's Table. These allow you to map two values to a third, just like a double-entry table.
Table<String,String,Double> currencyChanges = HashBasedTable.create();
currencyChanges.put("Euro", "US-Dollar", 1.2407);
currencyChanges.put("Euro", "Canadian Dollar", 1.5492);
...
// Later
Double currencyChange = currencyChanges.get(from, to);
solution = amout * currencyChange;
Note: you should use BigDecimal for monetary purposes, not doubles.
Consider selecting a base currency (e.g. the Euro) to base all of your calculations on. Create an enum based on each currency's value compared to the Euro:
public enum Currency
{
EUR(1.00),
USD(1.2407),
CAD(1.5492),
// Any other currencies you wish to support
}
Then, just take the amount you get and convert it to Euros, then to the final currency:
amount *= Currency.USD.ordinal() / Currency.CAD.ordinal();
Where USD is the original currency and CAD is the final currency.
You should save once in map with key fromCurrency + toCurrency and its value is the currency rate
Map<String, Double> currenciesRate = ...
And in your method just get the value
Double rate = currenciesRate.get(fromCurrency + toCurrency);
solution = amount*rate;
You will be better off using your own object as a key for the map.

How to extract the unit and subunit parts from the given amount of money represented in microunits?

I'm working on project in Java and have a price in micro-units.
A price in micro-units is a price, where 1,000,000 micro-units equal one unit of the currency. For example, if price is "€7.99", price_amount_micros is "7990000"
I need to extract 7 and 99 as separate strings. Having read some posts about rounding errors, I think the right way to achieve what I need is to convert the given amount to a string and extract the unit and subunit parts using the following regex:
^(\d+)(\d{2})0000$
However, for some reason, I feel like it's not an elegant way.
You can refine it to:
^(\d+)(\d{2})0{4}$
But then you are done imho.
I handle all Prices as INT in my Databases.
7.99 would be 799 there.
There are no Rounding-Errors.
It may look like an overkill but to be on safer side with floating point issues, you can use BigDecimal based logic as this:
void extractParts(String str) {
BigDecimal bd = new BigDecimal(str);
BigDecimal res = bd.scaleByPowerOfTen(-6);
BigDecimal rem = res.remainder(BigDecimal.ONE).stripTrailingZeros();
System.out.printf("<%s> <%s>%n", res.longValue(),
rem.movePointRight(rem.scale()).abs().longValue());
}
Then call it as:
extractParts("7990000");
//=> <7> <99>
extractParts("-1835000");
//=> <-1> <835>
extractParts("89000000");
//=> <89> <0>

Disable Java making big number smaller? (10,000,000,000 to 1E10)

I have a big number in a database; in this case, 10,000,000,000. Whenever I use that information for something, like sending a message with it, instead of 10,000,000,000, it says 1E10, and I really do not want that.
Can I avoid that in any way?
If I go to the database, the value is 10,000,000,000.
It's the same number, just represented in scientific notation.
Since you don't describe how you are storing the value, you can use DecimalFormat#getNumberInstance to help format it to one that doesn't contain the scientific notation.
double foo = 10000000000L;
System.out.println(foo);
System.out.println(DecimalFormat.getIntegerInstance().format(foo));
This outputs:
1.0E10
10,000,000,000

How to format numbers on Android

i am learning to program mobile aplications on Android. My first app is a unit converter. Everithing is working for now, but i have a question about formating numbers. I hava this code to get text from buttons and to convert the appropriet output:
if (bPrevodZ.getText() == "milimeter"){
if (bPrevodDo.getText()=="kilometer"){
String PomocnaPremenna = jednotkaZ.getText().toString();
double cisloNaPrevod = Double.parseDouble(PomocnaPremenna);
cisloNaPrevod = cisloNaPrevod*0.0000001;
vysledok.setText(Double.toString(cisloNaPrevod));
}
The final result is "cisloNaPrevod", but i have problems to show a good format of that number. For example:
12345 mm = 0,0012345 km this is good right ? :)
but if i convert:
563287 mm = 0.05632869999999995 this is bad :) i need it to show 0.0563287
Thx for any help
Use String.format:
String.format("%.6f", cisloNaPrevod);
If you want your number to always have 6 significant figures, use
vysledok.setText(String.format("%.6g", cisloNaPrevod));
giving the result 0.0563287.
If you want to round to 6 numbers after the decimal place, use
vysledok.setText(String.format("%.6f", cisloNaPrevod));
giving the result 0.056329.
Here's some good resources that cover number formatting:
Floating-point cheat sheet for Java
java.util.Formatter
If it's something you're going to do often, perhaps you should use DecimalFormat.
DecimalFormat df = new DecimalFormat("#.#######");
Then call:
df.format(someDoubleValue);

How do I effectively use the Modulus Operator in Java

I am doing a college assignment in Java that deals with currency. For that I am advised to use ints instead of doubles and then later convert it to a dollar value when I print out the statement.
Everything works fine until I do calculations on the number 4005 (as in $40.05 represented as an int). I am pasting the part of code I am having problems with, I would appreciate if someone could tell me what I am doing wrong.
import java.io.*;
class modumess {
public static void main(String[] args) {
int money = 4005; //Amount in cents, so $40.05;
// Represent as normal currency
System.out.printf("$%d.%d", money/100, money%100);
}
}
The above code, when run, shows $40.5, instead of $40.05. What gives?
Kindly note that this is for my homework and I want to learn, so I would really appreciate an explanation about the root of the problem here rather than just a simple solution.
EDIT: Following Finbarr's answer, I have added the following to the code which seems to have fixed the problem:
if (money%100 < 10) {
format = "$%d.0%d";
}
Is this a good way to do it or am I over-complicating things here?
EDIT: I just want to make it clear that it was both Finbarr and Wes's answer that helped me, I accepted Wes's answer because it made it clearer for me on how to proceed.
A better way would be something like this for a general case:
format = "%d.%02d";
%02d gives you 0 padding for 2 digits. That way you don't need the extra if statement.
See this for more explanation of things you can do in format: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html#syntax
The modulus operator returns the remainder after division without fractional calculation. In this case, 4005%100 returns 5 as the remainder of 4005/100 is 5.

Categories

Resources