s c h e m a t i c s : c o o k b o o k

/ WebHome / TOC / NumberChapter / Cookbook.NumberRecipesRounding

This Web


WebHome 
WebChanges 
TOC (with recipes)
NewRecipe 
WebTopicList 
WebStatistics 

Other Webs


Chicken
Cookbook
Erlang
Know
Main
Plugins
Sandbox
Scm
TWiki  

Schematics


Schematics Home
Sourceforge Page
SchemeWiki.org
Original Cookbook
RSS

Scheme Links


Schemers.org
Scheme FAQ
R5RS
SRFIs
Scheme Cross Reference
PLT Scheme SISC
Scheme48 SCM
MIT Scheme scsh
JScheme Kawa
Chicken Guile
Bigloo Tiny
Gambit LispMe
GaucheChez

Lambda the Ultimate
TWiki.org

Rounding Floating-Point Numbers

Problem

You need to round a floating-point number to an integer.

Solution

Use one of the procedures round, ceiling, floor and truncate.

(floor -4.3)     ==>  -5.0
(ceiling -4.3)   ==>  -4.0
(truncate -4.3)  ==>  -4.0
(round -4.3)     ==>  -4.0
     
(floor 3.5)      ==>  3.0
(ceiling 3.5)    ==>  4.0
(truncate 3.5)   ==>  3.0
(round 3.5)      ==>  4.0  ; inexact
     
(round 7/2)      ==>  4    ; exact
(round 7)        ==>  7

Discussion

The procedures all return integers.

The procedure round returns the closest integer to x, rounding to even when x is halfway between two integers.

The procedure floor returns the largest integer not larger than =x.

The procedure ceiling returns the smallest integer not smaller than x.

The procedure truncate returns the integer closest to x whose absolute value is not larger than the absolute value of x.

If the number given to one of the procedures is inexact?, then the result will also be inexact.

-- ChandraQuintas - 27 Apr 2004 -- JensAxelSoegaard - 10 May 2004

CookbookForm
TopicType: Recipe
ParentTopic: NumberRecipes
TopicOrder: 030

 
 
Copyright © 2004 by the contributing authors. All material on the Schematics Cookbook web site is the property of the contributing authors.
The copyright for certain compilations of material taken from this website is held by the SchematicsEditorsGroup - see ContributorAgreement & LGPL.
Other than such compilations, this material can be redistributed and/or modified under the terms of the GNU Lesser General Public License (LGPL), version 2.1, as published by the Free Software Foundation.
Ideas, requests, problems regarding Schematics Cookbook? Send feedback.
/ You are Main.guest