Reputation: 1193
How can I convert 42.0
to 42.00
in Scheme?
For Example (In Scheme):
When I do (/ 20.00 2)
, I get 10.0
. I want 10.00
as the result of above instead of 10.0
Upvotes: 1
Views: 9014
Reputation: 11
If you use racket, I think that could help.
(~r pi #:precision 4)
"3.1416"
Upvotes: 1
Reputation: 236114
The numbers 10.0
and 10.00
are exactly the same. Maybe you want to format your output to a string with a fixed number of decimals to the right of the dot? try this:
(define (right-pad number len)
(let* ((nstr (number->string number))
(diff (- len (string-length nstr)))
(pads (if (> diff 0) (make-string diff #\0) "")))
(string-append nstr pads)))
Use it like this:
(display (right-pad (/ 20.00 2) 5))
> 10.00
Notice that the len
parameter indicates the total amount of chars desired in the resulting string, including the dot. This solution has the advantage of being independent from external libraries.
Upvotes: 4
Reputation: 8523
Óscar's solution works well, but an even easier solution is to use SRFI-48, which provides additional format directives.
(display (format "~0,2F" (/ 20.00 2)))
Upvotes: 7
Reputation: 15769
The objects represented by 10.0
and 10.00
are the same. There is no such thing as a fixed-precision decimal number in R5RS Scheme. What do you need the fixed precision for? If it is relevant for output, you need to do formatted printing of some sort. Check your Scheme implementation's documentation about a printf
or format
function. If, on the other hand, you actually need decimal arithmetic, you will need to either use exact ratios and round explicitly according to the rules you want to use, or use integers and treat them as units of size 1/100.
Upvotes: 5