LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 03-07-2008, 10:04 PM   #1
rabbit2345
Member
 
Registered: Apr 2007
Location: SC
Distribution: Kubuntu 20.04 LTS
Posts: 378

Rep: Reputation: 41
use decimals in java?


hi,
I want to write a small program that averages some numbers together, but to do that, I can do the adding part, but I can't get the program to output a decimal. I f i use java.lang.Math.round(total,2) then i get this error message:

Code:
brian@brian-linux:~/Documents/java> javac avg.java
avg.java:514: cannot find symbol
symbol  : method Round(double,int)
location: class java.lang.Math
double round = java.lang.Math.round(total,2);
                   ^
1 error
did I do something wrong?

thanks,

rabbit2345
 
Old 03-08-2008, 12:08 AM   #2
nullmind
LQ Newbie
 
Registered: Mar 2008
Posts: 9

Rep: Reputation: 0
The Math.round method only takes one argument. It does not allow you to truncate based on decimal places. See the API reference:

http://java.sun.com/javase/6/docs/ap...l#round(double)

What you want can be accomplished like this though:

Code:
public class Sum{
	/**
		Usage: java Sum <number>...
	*/
	public static void main(String[] args){
		float sum = 0;
		
		for(String str : args){
			sum += Float.parseFloat(str);			
		}
		
		System.out.printf("%02.2f\n", sum);
	}
}
You could also surround the Float.parseFloat to catch the NumberFormatException if an invalid value is passed.

Cheers,
Kris
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
LXer: Java news met with cautious optimism in free Java community LXer Syndicated Linux News 0 11-14-2006 10:21 PM
how do I use "format" with "pipe" to format decimals Joseph Schiller Programming 1 12-23-2005 12:30 PM
how to compare decimals linuxboy69 Linux - Software 2 08-16-2004 02:43 PM
Can I use a lot of decimals in my C program? Golradir Programming 14 07-04-2004 12:40 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 04:50 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration