Decimal floating point number to binary: Difference between revisions

added RPL
(Added Sidef)
(added RPL)
 
(46 intermediate revisions by 19 users not shown)
Line 2:
 
;Task:
Create a program that takes a decimal [https://en.wikipedia.org/wiki/Floating-point_arithmetic#Floating-point_numbers floating point number] and displays its binary representation and vice versa: takes a floating point binary number and outputs its decimal representation.
 
 
Line 10:
<br><br>
 
=={{header|dc11l}}==
{{trans|Kotlin}}
{{works with|dc|1.3.95 (GNU bc 1.06.95)}}
Interactively:
<lang bash>$ dc
2o
23.34375 p
10111.01011000000000000
q
$ dc
2i
1011.11101
p
11.90625
q
$</lang>
 
<syntaxhighlight lang="11l">F decToBin(d)
Directly on the command line:
V whole = Int(floor(d))
<lang bash>$ dc -e '2o 23.34375 p'
V binary = bin(whole)‘.’
10111.01011000000000000
V dd = d - whole
$ dc -e '2i 1011.11101 p'
L dd > 0.0
11.90625
V r = dd * 2.0
$ echo '2o 23.34375 p' | dc
I r >= 1.0
10111.01011000000000000
binary ‘’= ‘1’
$ echo '2i 1011.11101 p' | dc
dd = r - 1
11.90625
E
$</lang>
binary ‘’= ‘0’
dd = r
R binary
 
F binToDec(s)
V num = Int(s.replace(‘.’, ‘’), radix' 2)
V den = Int(‘1’s.split(‘.’)[1].replace(‘1’, ‘0’), radix' 2)
R Float(num) / den
 
V d = 23.34375
print(d"\t => "decToBin(d))
V s = ‘1011.11101’
print(s"\t => "binToDec(s))</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
</pre>
 
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">
-- Decimal floating point number to binary (and vice versa)
-- J. Carter 2023 Apr
-- We'll presume the input is a string containing the image of the number in the appropriate base, and the output is the
-- image in the other base; using the language's conversion of numeric literals seems like cheating
-- Uses the PragmAda Reusable Components (https://github.com/jrcarter/PragmARC)
 
with Ada.Strings.Fixed;
with Ada.Text_IO;
with PragmARC.Unbounded_Numbers.Rationals;
 
procedure Dec_Bin_FP is
use PragmARC.Unbounded_Numbers.Rationals; -- Avoid losing any precision in the inputs
 
function To_Binary (Decimal : in String) return String is
(Image (Value (Decimal), Base => 2) );
 
function To_Decimal (Binary : in String) return String is
(Image (Value ("2#" & Binary & '#') ) );
 
Decimal : constant String := "23.34375";
Binary : constant String := "1011.11101";
Pi : constant String := "3.14159265358979323846264338327950288419716939937511";
begin -- Dec_Bin_FP
Ada.Text_IO.Put_Line (Item => Decimal & ' ' & To_Binary (Decimal) );
Ada.Text_IO.Put_Line (Item => Binary & ' ' & To_Decimal (Binary) );
Ada.Text_IO.Put_Line (Item => Pi & ' ' & To_Binary (Pi) );
end Dec_Bin_FP;
</syntaxhighlight>
 
{{out}}
<pre>
23.34375 10111.01011
1011.11101 11.90625
3.14159265358979323846264338327950288419716939937511 11.0010010000111111011010101000100010000101101000110000100011010011000100110001100110001010001011100000001101110000011100110100010010100100000010010011100000100010001010110010111101110111001101010111010110100001001100011101010110011100010011100000101110011010001111000010101010101101011011001000010100111011100010111000010011101110010100111100011001101011101101111111010101100100010110111101011100101101100101000100100011001011011000011001000011110100001101001011101001101101110101010011000110010100100000010010000111111110011000000000010101110110001110001110010110111000101110001010110101110111011001010111010111101111011110000101011000110010101011101010110110100011110010110101111111011111010110111101100111101111011011001101011010110011010110000010011100110000001011100111000110011001111000001000001101110100000010000110110000000110001001010111011110011000110010100010010100101000000011101001111010101011001000101010001111101001110110010101101110110110000000000011110111110011110101011010000101001010
</pre>
 
=={{header|bc}}==
 
<syntaxhighlight lang="bc">
obase = 2
scale=100
3.14159265358979323846264338327950288419716939937510
11.00100100001111110110101010001000100001011010001100001000110100110001001100011001100010100010111000000011011100000111001101000100101001000000100100111000001000100010011
 
From the manpage: "To enter a negative number, begin the number with '_'. '-' cannot be used for this, as it is a binary operator for subtraction instead."
<lang bash>$ dc -e '2o _23.34375 p'
-10111.01011000000000000
$ dc -e '2i _1011.11101 p'
-11.90625
$</lang>
 
</syntaxhighlight>
 
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.conv, std.array, std.string, std.range, std.algorithm, std.typecons;
 
immutable string[string] hex2bin, bin2hex;
Line 107 ⟶ 155:
y2.bin2dec.writeln;
writefln("%.6f", "1011.11101p+0".bin2dec);
}</langsyntaxhighlight>
{{out}}
<pre>1.011101011p+100
Line 114 ⟶ 162:
-23.3438
11.906250</pre>
 
=={{header|dc}}==
{{works with|dc|1.3.95 (GNU bc 1.06.95)}}
Interactively:
<syntaxhighlight lang="bash">$ dc
2o
23.34375 p
10111.01011000000000000
q
$ dc
2i
1011.11101
p
11.90625
q
$</syntaxhighlight>
 
Directly on the command line:
<syntaxhighlight lang="bash">$ dc -e '2o 23.34375 p'
10111.01011000000000000
$ dc -e '2i 1011.11101 p'
11.90625
$ echo '2o 23.34375 p' | dc
10111.01011000000000000
$ echo '2i 1011.11101 p' | dc
11.90625
$</syntaxhighlight>
 
From the manpage: "To enter a negative number, begin the number with '_'. '-' cannot be used for this, as it is a binary operator for subtraction instead."
<syntaxhighlight lang="bash">$ dc -e '2o _23.34375 p'
-10111.01011000000000000
$ dc -e '2i _1011.11101 p'
-11.90625
$</syntaxhighlight>
 
=={{header|Delphi}}==
{{Trans|Go}}
<syntaxhighlight lang="delphi">
program FloatToBinTest;
 
{$APPTYPE CONSOLE}
 
{$R *.res}
 
uses
System.SysUtils,
Math;
 
function IntToBin(value: Int64): string;
var
i, bit: Integer;
begin
Result := '';
 
for i := 63 downto 0 do
begin
bit := (value shr i) and 1;
if (bit = 0) and Result.IsEmpty then
Continue;
Result := Result + bit.ToString
end;
end;
 
function BinToInt(value: string): Int64;
var
i, Alength: Integer;
bit: Int64;
begin
Result := 0;
Alength := Length(value);
for i := Alength downto 1 do
begin
bit := ord(value[i] = '1');
Result := Result or (bit shl (Alength - i));
end;
end;
 
function FloatToBin(value: Extended): string;
var
int, bit: Int64;
f: Extended;
begin
int := Trunc(value);
Result := IntToBin(int);
 
f := Frac(value);
if f > 0 then
Result := Result + '.';
 
while f > 0 do
begin
f := f * 2;
bit := Trunc(f);
Result := Result + bit.ToString;
f := f - bit;
end;
end;
 
function BinToFloat(value: string): Extended;
var
num, den: Extended;
begin
if value.IndexOf('.') = -1 then
exit(BinToInt(value));
 
num := BinToInt(value.Replace('.', '', []));
den := BinToInt('1' + value.Split(['.'])[1].Replace('1', '0', [rfReplaceAll]));
 
Result := num / den;
end;
 
var
f: Extended;
s: string;
 
begin
f := 23.34375;
Writeln(Format('%.5f'^I' => %s', [f, FloatToBin(23.34375)]));
 
s := '1011.11101';
Writeln(Format('%s'^I' => %.5f', [s, BinToFloat('1011.11101')]));
 
Readln;
end.
</syntaxhighlight>
{{out}}
<pre>
23,34375 => 10111.01011
1011.11101 => 11,90625
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule RC do
def dec2bin(dec, precision\\16) do
[int, df] = case String.trim(dec) |> String.split(".") do
[int] -> [int, nil]
[int, df] -> [int, df]
end
{sign, int} = if String.first(int)=="-", do: String.split_at(int, 1), else: {"", int}
bin = sign <> (String.to_integer(int) |> Integer.to_string(2)) <> "."
if df && String.to_integer(df)>0 do
String.to_float("0."<>df) |> dec2bin(precision, bin)
else
bin <> "0"
end
end
defp dec2bin(fp, digit, bin) when fp==0.0 or digit<=0, do: bin
defp dec2bin(fp, digit, bin) do
fp = fp * 2
n = trunc(fp)
dec2bin(fp-n, digit-1, bin<>Integer.to_string(n))
end
def bin2dec(bin) do
[int, df] = case String.trim(bin) |> String.split(".") do
[int] -> [int, nil]
[int, df] -> [int, df]
end
{sign, int} = if String.first(int)=="-", do: String.split_at(int, 1), else: {"", int}
dec = sign <> (String.to_integer(int, 2) |> Integer.to_string)
dec <> if df && String.to_integer(df,2)>0 do
1..String.length(df)
|> Enum.reduce(String.to_integer(df, 2), fn _,acc -> acc / 2 end)
|> to_string
|> String.slice(1..-1)
else
".0"
end
end
end
 
data = ~w[23.34375 11.90625 -23.34375 -11.90625]
Enum.each(data, fn dec ->
bin = RC.dec2bin(dec)
dec2 = RC.bin2dec(bin)
:io.format "~10s => ~12s =>~10s~n", [dec, bin, dec2]
end)
 
data = ~w[13 0.1 -5 -0.25]
Enum.each(data, fn dec ->
bin = RC.dec2bin(dec)
dec2 = RC.bin2dec(bin)
:io.format "~10s => ~18s =>~12s~n", [dec, bin, dec2]
end)</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011 => 23.34375
11.90625 => 1011.11101 => 11.90625
-23.34375 => -10111.01011 => -23.34375
-11.90625 => -1011.11101 => -11.90625
13 => 1101.0 => 13.0
0.1 => 0.0001100110011001 =>0.0999908447
-5 => -101.0 => -5.0
-0.25 => -0.01 => -0.25
</pre>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">USING: interpolate io kernel math.parser sequences ;
 
: bin>dec ( x -- y )
number>string "0b${}p0" interpolate>string string>number ;
 
23.34375 dup >bin
1011.11101 dup bin>dec [ [I ${} => ${}I] nl ] 2bi@</syntaxhighlight>
{{out}}
<pre>
23.34375 => 1.011101011p4
1011.11101 => 11.90625
</pre>
 
=={{header|Fortran}}==
Line 122 ⟶ 381:
An alternative method is to present the text to the I/O system as with <code>READ (ACARD,*) X</code>, except that there is no facility for specifying any base other than ten. In a more general situation the text would first have to be scanned to span the number part, thus incurring double handling. The codes for hexadecimal, octal and binary formats do ''not'' read or write numbers in those bases, they show the bit pattern of the numerical storage format instead, and for floating-point numbers this is very different. Thus, Pi comes out as 100000000001001001000011111101101010100010001000010110100011000 in B64 format, not 11·0010010000111111011010101... Note the omitted high-order bit in the normalised binary floating-point format - a further complication.
 
The source is F77 style, except for the MODULE usage simply for some slight convenience in sharing DIGIT and not having to re-declare the type of EATNUM. <langsyntaxhighlight Fortranlang="fortran"> MODULE REBASE !Play with some conversions between bases.
CHARACTER*36 DIGIT !A set of acceptable digit characters.
PARAMETER (DIGIT = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") !Not only including hexadecimal.
Line 283 ⟶ 542:
END DO !On to the next test.
END DO !And another base.
END !Enough of that. </langsyntaxhighlight>
 
Rather than mess about with invocations, the test interprets the texts firstly as base ten sequences, then base two. It makes no complaint over encountering the likes of "666" when commanded to absorb according to base two. The placewise notation is straightforward: 666 = 6x2<sup>2</sup> + 6x2<sup>1</sup> + 6x2<sup>0</sup>
Line 309 ⟶ 568:
Base 10 -42. Digits: 2</pre>
Note again that a decimal value in binary is almost always a recurring sequence and that the ''exact'' decimal value of the actual binary sequence in the computer (of finite length) is not the same as the original decimal value. 23·34375 happens to be an exact decimal representation of a binary value whose digit count is less than that available to a double-precision floating-point variable. But although 1011·1101 has few digits, in decimal it converts to a recurring sequence in binary just as does 0·1.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' Expresses (or rounds) the fractional part to the same number of places in binary as the decimal to be converted.
' This is accurate for the numbers used in this exercise but in general would not be.
Function decToBin(d As Double) As String
Dim neg As String = ""
If d < 0.0 Then
d = -d
neg = "-"
End If
Dim i As Integer = Fix(d)
Dim f As Double = Frac(d)
If f = 0 Then
Return neg + Bin(i)
End If
Dim le As Integer = Len(Str(d)) - Len(Str(i)) - 1
Return neg + Bin(i) + "." + Bin(Fix((2.0 ^ le) * f + 0.5), le)
End Function
 
Function binToDec(s As String) As Double
If s = "" Then Return 0.0
Dim neg As Integer = 1
If Left(s, 1) = "-" Then
s = Mid(s, 2)
neg = -1
End If
Dim index As Integer = Instr(s, ".")
If index = 0 Then
Return ValLng("&B" + s) * neg
Else
Dim a As Integer = ValLng("&B" + Left(s, index - 1))
Dim b As Integer = ValLng("&B" + Mid(s, index + 1))
Dim le As Integer = Len(Mid(s, index + 1))
Return (a + b / (2.0 ^ le)) * neg
End If
End Function
 
Print "23.34375 => "; decToBin(23.34375)
Print "1011.11101 => " ; binToDec("1011.11101")
Print "-23.34375 => " ; decToBin(-23.34375)
Print "-1011.11101 => " ; binToDec("-1011.11101")
Print "64 => "; decToBin(64)
Print "-100001 => " ; binToDec("-100001")
Print
Print "Press any key to quit"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
-23.34375 => -10111.01011
-1011.11101 => -11.90625
64 => 1000000
-100001 => -33
</pre>
 
=={{header|Go}}==
{{trans|Kotlin}}
<syntaxhighlight lang="go">package main
 
import (
"fmt"
"math"
"strconv"
"strings"
)
 
func decToBin(d float64) string {
whole := int64(math.Floor(d))
binary := strconv.FormatInt(whole, 2) + "."
dd := d - float64(whole)
for dd > 0.0 {
r := dd * 2.0
if r >= 1.0 {
binary += "1"
dd = r - 1.0
} else {
binary += "0"
dd = r
}
}
return binary
}
 
func binToDec(s string) float64 {
ss := strings.Replace(s, ".", "", 1)
num, _ := strconv.ParseInt(ss, 2, 64)
ss = strings.Split(s, ".")[1]
ss = strings.Replace(ss, "1", "0", -1)
den, _ := strconv.ParseInt("1" + ss, 2, 64)
return float64(num) / float64(den)
}
 
func main() {
f := 23.34375
fmt.Printf("%v\t => %s\n", f, decToBin(f))
s := "1011.11101"
fmt.Printf("%s\t => %v\n", s, binToDec(s))
}</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
</pre>
 
=={{header|Haskell}}==
float to binary part only:
<langsyntaxhighlight lang="haskell">import Data.Char (intToDigit)
import Numeric (floatToDigits, showIntAtBase)
 
Line 320 ⟶ 687:
 
main :: IO ()
main = putStrLn $ dec2bin 23.34375</langsyntaxhighlight>
{{out}}
<pre>
Line 334 ⟶ 701:
Implementation:
 
<langsyntaxhighlight Jlang="j">b2b=:2 :0
NB. string to rational number
exp=. (1x+y i.'.')-#y
Line 344 ⟶ 711:
s=. exp&(}.,'.',{.) (":m#.inv mant)-.' '
((exp-1)>.-+/*/\|.s e.'.0') }. s
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight Jlang="j"> 2 b2b 10 '23.34375'
10111.01011
10 b2b 2 '1011.11101'
11.90625</langsyntaxhighlight>
 
=={{header|Java}}==
 
Precision is not discussed. Most decimal fractional values are not representable in binary. For example, .1 in decimal is a repeating decimal in binary, with a value of .0[0011]... in binary. As a result, a precision of 50 digits is the default. However, this is a helper method and the actual implementation uses the specified precision.
 
<syntaxhighlight lang="java">
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
 
public class DecimalToBinary {
 
public static void main(String[] args) {
for ( String s : new String[] {"23.34375", ".1", "3.1415926535897932"} ) {
String binary = decimalToBinary(new BigDecimal(s));
System.out.printf("%s => %s%n", s, binary);
System.out.printf("%s => %s%n", binary, binaryToDecimal(binary));
}
}
 
private static BigDecimal binaryToDecimal(String binary) {
return binaryToDecimal(binary, 50);
}
 
private static BigDecimal binaryToDecimal(String binary, int digits) {
int decimalPosition = binary.indexOf(".");
String integer = decimalPosition >= 0 ? binary.substring(0, decimalPosition) : binary;
String fractional = decimalPosition >= 0 ? binary.substring(decimalPosition+1) : "";
 
// Integer part
BigDecimal result = BigDecimal.ZERO;
BigDecimal powTwo = BigDecimal.ONE;
BigDecimal two = BigDecimal.valueOf(2);
for ( char c : new StringBuilder(integer).reverse().toString().toCharArray() ) {
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')));
powTwo = powTwo.multiply(two);
}
// Fractional part
MathContext mc = new MathContext(digits);
powTwo = BigDecimal.ONE;
for ( char c : fractional.toCharArray() ) {
powTwo = powTwo.divide(two);
result = result.add(powTwo.multiply(BigDecimal.valueOf(c - '0')), mc);
}
return result;
}
private static String decimalToBinary(BigDecimal decimal) {
return decimalToBinary(decimal, 50);
}
private static String decimalToBinary(BigDecimal decimal, int digits) {
BigDecimal integer = decimal.setScale(0, RoundingMode.FLOOR);
BigDecimal fractional = decimal.subtract(integer);
StringBuilder sb = new StringBuilder();
 
// Integer part
BigDecimal two = BigDecimal.valueOf(2);
BigDecimal zero = BigDecimal.ZERO;
while ( integer.compareTo(zero) > 0 ) {
BigDecimal[] result = integer.divideAndRemainder(two);
sb.append(result[1]);
integer = result[0];
}
sb.reverse();
// Fractional part
int count = 0;
if ( fractional.compareTo(zero) != 0 ) {
sb.append(".");
}
while ( fractional.compareTo(zero) != 0 ) {
count++;
fractional = fractional.multiply(two);
sb.append(fractional.setScale(0, RoundingMode.FLOOR));
if ( fractional.compareTo(BigDecimal.ONE) >= 0 ) {
fractional = fractional.subtract(BigDecimal.ONE);
}
if ( count >= digits ) {
break;
}
}
return sb.toString();
}
 
}
</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011
10111.01011 => 23.34375
.1 => .00011001100110011001100110011001100110011001100110
.00011001100110011001100110011001100110011001100110 => 0.09999999999999964472863211994990706443786621093750
3.1415926535897932 => 11.00100100001111110110101010001000100001011010001100
11.00100100001111110110101010001000100001011010001100 => 3.1415926535897931159979634685441851615905761718750
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">""" Convert numeric string in base 10 to base 2 floating point string """
function dec2bin(x::String)
bx = parse(BigFloat, x)
xneg = bx >= 0 ? false : true
bx = BigFloat(xneg ? -bx : bx)
pre, post, n = "", "", div(nextpow(2, bx), 2)
while bx > 0
a, bx = divrem(bx, BigFloat(n))
if n >= 1
pre *= a > 0 ? '1' : '0'
else
post *= a > 0 ? '1' : '0'
end
n /= 2.0
end
(xneg ? "-" : "") * pre * "." * post
end
 
""" Convert binary floating point format string to Float64 numeric type """
function bin2dec(binfloat::String)
binfloat = strip(binfloat)
if binfloat[1] == '-'
binfloat = binfloat[2:end]
xneg = -1
else
xneg = 1
end
if occursin(".", binfloat)
(pre, post) = split(binfloat, ".")
mult = BigInt(2)^length(post)
return xneg * (BigFloat(parse(BigInt, pre, base=2)) +
BigFloat(parse(BigInt, post, base=2) / mult))
else
return xneg * BigFloat(parse(BigInt, binfloat, base=2))
end
end
function testconversions(tdata)
println("String (base 10) Base 2 Base 10")
for dstring in testdata
b2 = dec2bin(dstring)
b10 = bin2dec(b2)
println(lpad(dstring, 10), lpad(b2, 18), lpad(b10, 10))
end
end
 
testdata = ["23.34375", "11.90625", "-23.34375", "-11.90625"]
testconversions(testdata)
</syntaxhighlight>{{out}}
<pre>
String (base 10) Base 2 Base 10
23.34375 10111.01011 23.34375
11.90625 1011.11101 11.90625
-23.34375 -10111.01011 -23.34375
-11.90625 -1011.11101 -11.90625
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.0
 
fun decToBin(d: Double): String {
val whole = Math.floor(d).toLong()
var binary = whole.toString(2) + "."
var dd = d - whole
while (dd > 0.0) {
val r = dd * 2.0
if (r >= 1.0) {
binary += "1"
dd = r - 1
}
else {
binary += "0"
dd = r
}
}
return binary
}
 
fun binToDec(s: String): Double {
val num = s.replace(".", "").toLong(2)
val den = ("1" + s.split('.')[1].replace("1", "0")).toLong(2)
return num.toDouble() / den
}
 
fun main(args: Array<String>) {
val d = 23.34375
println("$d\t => ${decToBin(d)}")
val s = "1011.11101"
println("$s\t => ${binToDec(s)}")
}</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
</pre>
 
=={{header|Ksh}}==
<syntaxhighlight lang="ksh">
#!/bin/ksh
 
# Decimal floating point number to binary
 
# # Variables:
#
 
# # Functions:
#
 
# # Function _fpdec2bin(n.d) - return binary of floating point decimal n.d
#
function _fpdec2bin {
typeset _fp ; _fp=$1
typeset _base ; integer _base=2
typeset _n _q _r _whole _fract ; integer _n _q _r
typeset _p _d ; float _p _d=.0
typeset -a _arr _barr
 
_n=${_fp%\.*}
[[ ${_fp} == +(\d)\.*(\d) ]] && _d=${_fp#*${_n}}
 
(( _q = _n / _base ))
(( _r = _n % _base ))
_arr+=( ${_r} )
until (( _q == 0 )); do
_n=${_q}
(( _q = _n / _base ))
(( _r = _n % _base ))
_arr+=( ${_r} )
done
_revarr _arr _barr
_whole=${_barr[@]} ; _whole=${_whole// /}
 
(( _p = _d * _base ))
unset _q ; _q=${_p%\.*}
_fract="${_q}" ; float _q
(( _d = _p - _q ))
until (( ${_d} == 0.0 )); do
(( _p = _d * _base ))
unset _q ; _q=${_p%\.*}
_fract+=${_q} ; float _q
(( _d = _p - _q ))
done
 
echo "${_whole}.${_fract}"
}
 
# # Function _fpbin2dec(b) - return floating point decimal for binary b
#
function _fpbin2dec {
typeset _b ; _b=$1
[[ ${_b} != *(0|1)*(\.)*(0|1) ]] && return 1
 
typeset _m ; _m=${_b%\.*} # Before the .
typeset _d ; _d=${_b#*\.} # After the .
typeset _i _p _base ; typeset -si _i _p=0 _base=2
typeset _msum ; typeset -si _msum=0
typeset _psum ; float _psum=0
 
for ((_i=${#_m}-1; _i>=0; _i--)); do
(( ${_m:_i:1} )) && (( _msum+=(_base**_p) ))
(( _p++ ))
done
 
_p=1
for ((_i=0; _i<${#_d}; _i++)); do
(( ${_d:_i:1} )) && (( _psum+=(1.0 / (_base**_p)) ))
(( _p++ ))
done
echo "${_msum}.${_psum#*0\.}"
}
 
# # Function _revarr(arr, barr) - reverse arr into barr
#
function _revarr {
typeset _arr ; nameref _arr="$1"
typeset _barr ; nameref _barr="$2"
typeset _i ; integer _i
 
for ((_i=${#_arr[*]}-1; _i>=0; _i--)); do
_barr+=( ${_arr[_i]} )
done
}
 
######
# main #
######
 
print "Floating point decimal to Binary conversion:"
print "23.34375 => $(_fpdec2bin 23.34375)"
print "11.90625 => $(_fpdec2bin 11.90625)"
 
print "\nFloating point binary to decimal conversion:"
print "10111.01011 => $(_fpbin2dec 10111.01011)"
print "1011.11101 => $(_fpbin2dec 1011.11101)"
</syntaxhighlight>
{{out}}<pre>
Floating point decimal to Binary conversion:
23.34375 => 10111.01011
11.90625 => 1011.11101
 
Floating point binary to decimal conversion:
10111.01011 => 23.34375
1011.11101 => 11.90625</pre>
 
=={{header|LiveCode}}==
LiveCode's baseConvert only works on integers.
Only the first part of this task is complete.
<langsyntaxhighlight LiveCodelang="livecode">function float2bin n
put 15 into limit
put 0 into i
Line 373 ⟶ 1,047:
 
put float2bin(23.34375) // 10111.01011
put float2bin(11.90625) //1011.11101</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module Checkit {
Conv2dec=lambda (n$, frombase=10, dp$=".") -> {
neg=left$(n$,1)="-": if neg then n$=mid$(n$,2)
if instr(n$, dp$)>0 then {
n2$=Piece$(n$,dp$,2)
n$=Piece$(n$, dp$,1)
} else n2$=""
n0=0
l1=len(n$)+1
For i=len(n$) to 1
dig$=Mid$(n$,l1-i,1)
dig=asc(dig$)-48
if dig$>"9" then dig-=7
if dig>=frombase then error "not in base:"+frombase
n0+=dig*frombase^(i-1)
next i
if n2$<>"" then {
For i=1 to len(n2$)
dig$=Mid$(n2$,i,1)
dig=asc(dig$)-48
if dig$>"9" then dig-=7
if dig>=frombase then error "not in base:"+frombase
n0+=dig/frombase^i
Next i
}
if neg then n0-!
=n0
}
Conv2Any$=Lambda$ (dec, tobase=10, dp$=".", prec=16) -> {
a$=""
neg=false
if dec<0 then neg=true
dec=abs(dec)
n2=frac(dec)
if dec=0 then {
a$="0"
} else {
do {
n=dec mod tobase
if n>=10 then n+=7
a$=chr$(n+48)+a$
dec=dec div tobase
} until dec==0
}
if n2<>0 then {
a$+=dp$
prec--
do {
prec--
dec=n2*tobase
n2=frac(dec)
dec-=n2
n2=round(n2)
if dec>=10 then dec+=7
a$+=chr$(dec+48)
} until n2=0 or prec<0
}
if neg then {="-"+a$} else =a$
}
Rem : Locale 1033 ' use . for all print out for decimal point
Print Conv2dec("10111.01011",2); " => ";Conv2Any$(23.34375,2)
Print Conv2Any$(11.90625, 2); " => "; Conv2dec("1011.11101",2)
\\ using , for decimal point
Print Conv2Any$(Conv2dec("1011,11101",2, ","), 10, ",")
Print 12312321.1212
Print Conv2Any$(12312321.1212, 2)
\\ using . for 1033 locale
Print Str$(Conv2Dec(Conv2Any$(12312321.1212, 2), 2), 1033)="12312321.1211853"
Print Str$(Conv2Dec(Conv2Any$(12312321.1212, 2,,52), 2), 1033) ="12312321.1212"
}
Checkit
</syntaxhighlight>
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
11,90625
12312321.1212
101110111101111100000001.0001111100000110
True
True
</pre>
 
=={{header|Maple}}==
<syntaxhighlight lang="maple">
<lang Maple>
convert(23.34375,binary,decimal);
 
convert(1011.11101,decimal,binary);
</syntaxhighlight>
</lang>
Output:
<pre>
Line 388 ⟶ 1,147:
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">dec2bin[x_] := Block[{digits, pos},
{digits, pos} = (RealDigits[ToExpression@x, 2] /. {a_, b_} :> {ToString /@ a, b});
StringJoin @@
Join@{Take[digits, pos], {"."}, Quiet@NestWhile[Most, Drop[digits, pos], Last@# === "0" &]}]
 
bin2dec[x_] := FromDigits[RealDigits@ToExpression@x, 2] // N
 
Print[NumberForm[#, {9, 5}], " => ", dec2bin@#] &@23.34375;
Print[NumberForm[#, {9, 5}], " => ", NumberForm[bin2dec@#, {9, 5}]] &@1011.11101;</langsyntaxhighlight>
{{out}}
<pre>23.34375 => 10111.01011
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625</pre>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<syntaxhighlight lang="nim">import math, strutils
 
func decToBin(f: float): string =
let parts = f.splitDecimal()
result = int(parts[0]).toBin(64).strip(trailing = false, chars = {'0'}) & '.'
var d = parts[1]
while d > 0.0:
let r = d * 2
if r >= 1:
result.add '1'
d = r - 1
else:
result.add '0'
d = r
 
func binToDec(s: string): float =
let num = fromBin[int](s.replace(".", ""))
let den = fromBin[int]('1' & s.split('.')[1].replace('1', '0'))
result = num / den
 
when isMainModule:
 
let d = 23.34375
echo d, " → ", decToBin(d)
let s = "1011.11101"
echo s, " → ", binToDec(s)</syntaxhighlight>
 
{{out}}
<pre>23.34375 → 10111.01011
1011.11101 → 11.90625</pre>
 
=={{header|OCaml}}==
Line 411 ⟶ 1,199:
program should perform conversions from any base to any other base.
{{works with|OCaml|4.03+}}
<langsyntaxhighlight lang="ocaml">
#load "str.cma"
(* Using the interpteter or the compiler:
Line 654 ⟶ 1,442:
and _ = List.iter (fun tpl -> print_endline (testit tpl)) values
in ()
</syntaxhighlight>
</lang>
{{out}}
23.343750 => 10111.01011; expected 10111.01011 [PASS]
Line 681 ⟶ 1,469:
23.700000 => 23.700000; expected 23.700000 [PASS]
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">use strict;
use warnings;
use feature 'say';
 
sub dec2bin {
=={{header|Perl 6}}==
my($l,$r) = split /\./, shift;
<lang perl6>given "23.34375" { say "$_ => ", :10($_).base(2) }
my $int = unpack('B*', pack('N', $l ));
given "1011.11101" { say "$_ => ", :2($_).base(10) }</lang>
my $frac = unpack('B32', pack('N',4294967296 * ".$r"));
"$int.$frac" =~ s/^0*(.*?)0*$/$1/r;
}
 
sub bin2dec {
my($l,$r) = split /\./, shift;
my $frac = my $i = 0;
--$i, $frac += $_ * 2**$i for split '', $r;
eval('0b'.$l) + $frac;
}
 
say dec2bin(23.34375);
say bin2dec('1011.11101');</syntaxhighlight>
{{out}}
<pre>23.34375 => 10111.01011
1011.11101 => 11.90625</pre>
 
=={{header|Phix}}==
Handles bases 2..36. Does not handle any form of scientific notation.
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">dec_to</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- convert d to a string in the specified base
-- eg dec_to(65535,16) =&gt; "FFFF"</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">neg</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">d</span><span style="color: #0000FF;"><</span><span style="color: #000000;">0</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">neg</span> <span style="color: #008080;">then</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">d</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">whole</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">-=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #004600;">true</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mod</span><span style="color: #0000FF;">(</span><span style="color: #000000;">whole</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">+=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">></span><span style="color: #000000;">9</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ch</span><span style="color: #0000FF;">&</span><span style="color: #000000;">res</span>
<span style="color: #000000;">whole</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">whole</span><span style="color: #0000FF;">/</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">whole</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'.'</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span>
<span style="color: #008080;">and</span> <span style="color: #0000FF;">(</span><span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">8</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">,</span><span style="color: #000000;">32</span><span style="color: #0000FF;">})</span> <span style="color: #008080;">or</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">15</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">base</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">digit</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">digit</span>
<span style="color: #000000;">digit</span> <span style="color: #0000FF;">+=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">digit</span><span style="color: #0000FF;">></span><span style="color: #000000;">9</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">digit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">neg</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">'-'</span><span style="color: #0000FF;">&</span><span style="color: #000000;">res</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">to_dec</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- convert the string s (in the specified base)
-- back into a normal decimal/floating point.
-- eg to_dec("FFFF",16) =&gt; 65535</span>
<span style="color: #004080;">bool</span> <span style="color: #000000;">neg</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]=</span><span style="color: #008000;">'-'</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">neg</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">..$]</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">dot</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'.'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">dot</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">..</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">-=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">>=</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">?</span><span style="color: #008000;">'A'</span><span style="color: #0000FF;">-</span><span style="color: #000000;">10</span><span style="color: #0000FF;">:</span><span style="color: #008000;">'0'</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">res</span><span style="color: #0000FF;">*</span><span style="color: #000000;">base</span> <span style="color: #0000FF;">+</span> <span style="color: #000000;">ch</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">dot</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">/=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">neg</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">res</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">procedure</span> <span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">base</span><span style="color: #0000FF;">=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dec_to</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">g</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">to_dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">f</span><span style="color: #0000FF;">-</span><span style="color: #000000;">g</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">e</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #008000;">""</span><span style="color: #0000FF;">:</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">" (error: %g)"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%.8g =&gt; 0(%d):%s =&gt; %.8g%s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">base</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">23.34375</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">23.34375</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">11.90625</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">11.90625</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">5</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(-</span><span style="color: #000000;">0.25</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">65535</span><span style="color: #0000FF;">,</span><span style="color: #000000;">16</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">(</span><span style="color: #000000;">23.7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">35</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">to_dec</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"23.7"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">dec_to</span><span style="color: #0000FF;">(</span><span style="color: #000000;">23.7</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
23.34375 => 0(2):10111.01011 => 23.34375
-23.34375 => 0(2):-10111.01011 => -23.34375
11.90625 => 0(2):1011.11101 => 11.90625
-11.90625 => 0(2):-1011.11101 => -11.90625
13 => 0(2):1101 => 13
0.1 => 0(2):0.0001100110011001100110011001100110011001100110011001101 => 0.1
-5 => 0(2):-101 => -5
-0.25 => 0(2):-0.01 => -0.25
0 => 0(2):0 => 0
65535 => 0(16):FFFF => 65535
23.7 => 0(35):N.OHHHHHHHHFIVE => 23.7 (error: -3.55271e-15)
23.7
"23.699999999999"
</pre>
Aside: I was quite surprised to get 100% accuracy on these tests, but actually it is more of
a lucky coincidence in the way it is written, as the last few tests show.<br>
The truth of the matter is simply that you ''can'' extract a float to a binary text representation exactly,
in a way that you just cannot do for most other (ie non-power-2) bases.<br>
Update: Added a limiter for non-base-2 fractions, as per 1/3 -> 0.333 forever in decimal.
Base 2/4/8/16/32 are guaranteed to terminate anyway, but for other bases we need some limit -
the 15 that I opted for is completely arbitrary.
 
===shorter===
Inspired by Kotlin/Go/Wren (no attempt to handle signs, nor will it handle no-dot properly)
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">dec2bin</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">whole</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">trunc</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%b."</span><span style="color: #0000FF;">,</span><span style="color: #000000;">whole</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">whole</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">d</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">*=</span> <span style="color: #000000;">2</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">bit</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">>=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'0'</span><span style="color: #0000FF;">+</span><span style="color: #000000;">bit</span>
<span style="color: #000000;">d</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">bit</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">bin2dec</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">dot</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'.'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">dot</span> <span style="color: #008080;">then</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">..</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">to_number</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">inbase</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">dot</span> <span style="color: #008080;">then</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">/=</span> <span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">dot</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">f</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">23.34375</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dec2bin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">f</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">g</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bin2dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">t</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"1011.11101"</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">bin2dec</span><span style="color: #0000FF;">(</span><span style="color: #000000;">t</span><span style="color: #0000FF;">),</span>
<span style="color: #000000;">u</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dec2bin</span><span style="color: #0000FF;">(</span><span style="color: #000000;">h</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%.5f =&gt; %s =&gt; %.5f\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">g</span><span style="color: #0000FF;">})</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s =&gt; %.5f =&gt; %s\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">t</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">u</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
23.34375 => 10111.01011 => 23.34375
1011.11101 => 11.90625 => 1011.11101
</pre>
 
=={{header|Python}}==
Python has float.hex() and float.fromhex() that can be used to form our own binary format.
<langsyntaxhighlight lang="python">hex2bin = dict('{:x} {:04b}'.format(x,x).split() for x in range(16))
bin2hex = dict('{:b} {:x}'.format(x,x).split() for x in range(16))
 
Line 723 ⟶ 1,665:
hx = (('-' if neg else '') + '0x' + hx + bn2[p:p+2]
+ str(int('0b' + bn2[p+2:], 2)))
return float.fromhex(hx)</langsyntaxhighlight>
 
{{out}}
Line 744 ⟶ 1,686:
=={{header|Racket}}==
The binary to number conversion is easy because it's supported by Racket. We can use <code>string-&gt;number</code>, wrap it in a dedicated function or use the read extension.
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(define (string->number/binary x)
Line 754 ⟶ 1,696:
#b0.01
(string->number "0.01" 2)
(newline)</langsyntaxhighlight>
{{out}}
<pre>2.3125
Line 762 ⟶ 1,704:
0.25</pre>
Racket only supports the number to binary conversion for integer numbers, so we multiply the original number by a power of two, to get all the binary digits, and then we manipulate the string to place the point in the correct place.
<langsyntaxhighlight Racketlang="racket">(define (number->string/binary x)
(define decimals-places 10)
(define digits-all (~r (inexact->exact (round (* x (expt 2 decimals-places))))
Line 781 ⟶ 1,723:
(number->string/binary 9)
(number->string/binary 0.01)
(newline)</langsyntaxhighlight>
{{out}}
<pre>"1001.000000101"
Line 787 ⟶ 1,729:
"0.000000101"</pre>
Some additional interesting examples
<langsyntaxhighlight Racketlang="racket">(number->string/binary (string->number/binary "010110.0011010"))
(string-&gt;number/binary (number->string/binary .1))
(newline)
 
(number->string/binary (string->number/binary "0.11111111111"))
(string->number/binary "0.11111111111")</langsyntaxhighlight>
{{out}}
<pre>"10110.001101000"
Line 799 ⟶ 1,741:
"1.000000000"
0.99951171875</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>given "23.34375" { say "$_ => ", :10($_).base(2) }
given "1011.11101" { say "$_ => ", :2($_).base(10) }</syntaxhighlight>
{{out}}
<pre>23.34375 => 10111.01011
1011.11101 => 11.90625</pre>
 
=={{header|REXX}}==
===version 1===
This REXX version will handle any number of digits, with&nbsp; basesand upwith to&nbsp; 242''any'' (using&nbsp; extendedbase ASCIIup characters).to '''242'''
(using extended ASCII characters).
Bases up to 62 will just use decimal digits along with upper and lowercase (Latin) letters.
 
This REXX program is a modified version of the original program which can handle ''any'' base (no limit),
Bases up to '''62''' will just use decimal digits along with upper and lowercase
and the original program did more extensive error checking.
(Latin) letters.
This program handles numbers with leading signs ('''-''', '''+''').
 
Bases that are negative are also supported (which won't be explained here).
This REXX program is a modified version of the original program which can
<lang rexx>/*REXX programs converts any number in a base to another base; bases≤242*/
handle &nbsp; ''any'' &nbsp; base (no limit), &nbsp; and the original
parse arg number toBase inBase digits .
<br>program did more extensive error checking.
if toBase=='' | toBase==',' then toBase=10 /*Specified? No, use default*/
 
if inBase=='' | inBase==',' then inBase=10 /* " " " " */
This program handles numbers with a leading sign ('''-''', '''+''') and preserves the sign.
if digits=='' | digits==',' then digits=60 /* */
 
if number=='' | number==',' then call err 'no number specified.'
''Bases'' &nbsp; that are &nbsp; ''negative'' &nbsp; are also supported &nbsp; (which won't
if \datatype(toBase,'W') then call err 'invalid toBase: ' toBase
be explained here).
if \datatype(inBase,'W') then call err 'invalid inBase: ' inBase
 
if \datatype(digits,'W') then call err 'invalid digits: ' digits
 
numeric digits max(digits,length(number))+5 /*use a bigger numeric digs.*/
This REXX version used a single function &nbsp; ('''base''') &nbsp; to
$=base(number,toBase,inBase) /*convert the number given. */
perform the base conversions.
numeric digits digits /*use a smaller numeric digs*/
 
if toBase==10 then if pos('.',$)\==0 then $=format($) /*maybe use BIF*/
Quite a bit of additional code was added to:
say number ' (in base' inBase") = " $ ' (in base' toBase")."
::* &nbsp; verify that the number &nbsp; (and other arguments) &nbsp; are valid
exit /*stick a fork in it, we're done.*/
::* &nbsp; check if the number has too many signs
/*──────────────────────────────────BASE subroutine─────────────────────*/
::* &nbsp; check if the number has too many decimal points
base: procedure; parse arg x 1 s 2 1 ox,tt,ii
::* &nbsp; check if the number is just a bare decimal point
@#=0123456789; @abc='abcdefghijklmnopqrstuvwxyz'; @abcu=@abc; upper @abcu
::* &nbsp; check if the number is null
dontUse=@#'.+-'@abc || @abcu"0708090a0b0c0d"x; OK=@# || @abcu || @abc
::* &nbsp; check for invalid digits/numerals for the specified base
$=OK||space(translate(xrange('1'x,"fe"x),,dontUse),0) /*max base string.*/
::* &nbsp; check for invalid &nbsp; '''TO''' &nbsp; base
m=length($)-1 /*"M" is the maximum base. */
::* &nbsp; check for invalid &nbsp; '''IN''' &nbsp; base
if tt=='' then tt=10 /*assume base 10 if omitted.*/
::* &nbsp; etc.
if ii=='' then ii=10 /*assume base 10 if omitted.*/
 
i=abs(ii); t=abs(tt)
The number of digits (numerals) in the result may be specified &nbsp; (for
if t==999 | t=="*" then t=m
continued fractions). &nbsp; The default is '''60'''.
if t>m then call err 'invalid range for ToBase:' t"; the range is: " 2 m
if i>m then call err 'invalid range for InBase:' i"; the range is: " 2 m
!=substr($,1+10*(tt<0),t) /*character string for base.*/
if tt<0 then !=0 || ! /*prefix a zero if neg base.*/
if x=='' then return left(!,t)
@=substr($, 1+10*(ii<0), i) /*@ =legal chars for base X.*/
oS= /*original sign placeholder.*/
if s='-' | s="+" then do /*process the sign (if any).*/
x=substr(x,2) /*strip the sign character. */
oS=s /*save the original sign. */
end
if (ii>10 & ii<37) | (ii<0 & ii>-27) then upper x /*uppercase it ? */
if pos('-',x)\==0 |, /*too many minus signs ? */
pos('+',x)\==0 |, /*too many plus signs ? */
x=='.' |, /*is single decimal point ? */
x=='' then call err 'illegal number: ' ox
parse var x w '.' g /*sep whole from fraction. */
if pos('.',g)\==0 then call err 'illegal number: ' ox /*too many . */
items.1=0 /*# of whole part "digits". */
items.2=0 /*# of fractional "digits". */
__=w||g /*verify re-composed number.*/
_=verify(__,@'.') /*# have any unusual digits?*/
if _\==0 then call err 'illegal char in number:' ox 'char=' substr(__,_,1)
if i\==10 then do /*convert # base I──►base 10*/
_=0; p=0 /*convert the whole # part. */
do j=length(w) to 1 by -1 while w\==''
_=_ + ((pos(substr(w,j,1),@)-1) * i**p)
p=p+1 /*increase power of the base*/
end /*j*/
w=_; _=0; p=1 /*convert fractional part. */
do j=1 for length(g);_=_+((pos(substr(g,j,1),@)-1)/i**p)
p=p+1 /*increase power of the base*/
end /*j*/
g=_
end
else if g\=='' then g="."g /*reinsert period if needed.*/
 
This REXX program can handle any sized number &nbsp; (as per the number of digits/numerals) &nbsp; that can be entered at the
if t\==10 then do /*convert base10 # to base T*/
<br>command line.
if w\=='' then do /*convert whole number part.*/
<syntaxhighlight lang="rexx">/*REXX pgm converts any number in a base to another base including fractions; bases≤242.*/
do j=1; _=t**j; if _>w then leave
parse arg number toBase inBase digits . /*obtain optional arguments from the end /*jCL*/
if toBase=='' | toBase=="," then toBase= 10 /*Not specified? Then use the default.*/
n=
if inBase=='' | inBase=="," then inBase= 10 /* " " " " do" k=j-1 to 1 by -1;" _=t**k; d=w%_/
if digits=='' | digits=="," then digits= 60 /* " " " " n=n" || substr(!,1+d,1) " */
if number=='' | number=="," then call err "no number specified."
w=w//_ /*modulus = // */
if \datatype(toBase, 'W') then call err "invalid toBase: " toBase
end /*k*/
if \datatype(inBase, 'W') then call err "invalid inBase: " inBase
w=n||substr(!,1+w,1)
if \datatype(digits, 'W') then call err "invalid digits: " digits
end
numeric digits max(digits, length(number)) + 5 /*use a bigger numeric decimal digits. */
if g\=='' then do; n= /*convert fractional part. */
$= base(number, toBase, inBase) /*convert the # from a base to a base. do digits()+1 while g\==0*/
numeric digits digits /*use a smaller numeric p=gdigs*t; g=p//1; d=p%1
if toBase==10 then if pos(., $)\==0 then $= format($) /*maybe use the FORMAT BIF.*/
n=n || substr(!,d+1,1)
say number ' (in base' inBase") = " $ ' (in base' end /*digits(toBase")+1 ···*/."
exit if n==0 then n= /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
if n\=='' then n='.'n /*only a fraction?*/
base: procedure; parse arg x 1 s 2 1 ox,tt,ii,,oS
g=n
@#= 0123456789; @abc= 'abcdefghijklmnopqrstuvwxyz'; @abcu= @abc; upper end@abcu
dontUse= @#'.+-'@abc || @abcu"0708090a0b0c0d"x; OK= @# || @abcu || @abc
end
$= OK || space( translate( xrange('1'x, "fe"x), , dontUse), 0) /*max base string*/
return oS || word(strip(space(w),'L',0)strip(strip(g,,0),"T",'.') 0,1)
m= length($) - 1 /*M: is the maximum base. */
/*──────────────────────────────────ERR subroutine──────────────────────*/
if tt=='' then tt= 10 /*assume base 10 if omitted.*/
err: say; say '***error!***: ' arg(1); say; exit 13</lang>
if ii=='' then ii= 10 /*assume base 10 if omitted.*/
'''output''' when using the input of: <tt> 23.34375 2 </tt>
i= abs(ii); t= abs(tt) /*use absolute values for I&T*/
if t==999 | t=="*" then t= m /*T=999 or *? Then use max.*/
if t>m then call err 'invalid range for ToBase:' t"; the range is: " 2 m
if i>m then call err 'invalid range for InBase:' i"; the range is: " 2 m
!= substr($, 1 + 10 * (tt<0), t) /*character string for base. */
if tt<0 then != 0 || ! /*Net base? Prefix a zero. */
if x=='' then return left(!, t) /*Is X null? Show base chars*/
@=substr($, 1 + 10 * (ii<0), i) /*@: legal chars for base X.*/
if s='-' | s="+" then do; x= substr(x, 2); oS= s /*elide the sign character, */
end /* ··· and save the original·*/
if (ii>10 & ii<37) | (ii<0 & ii>-27) then upper x /*should X be uppercased ? */
parse var x w '.' g /*sep whole from fraction. */
if pos('-', x)>0 | pos("+", x)>0 | x==. | x=='' | , /*too many signs, bare . or*/
pos(., g)>0 then call err 'illegal number: ' ox /*too many decimal points ? */
__=w || g; _= verify(__, @'.') /*# have any unusual digits? */
if _\==0 then call err 'illegal char in number:' ox 'char=' substr(__, _, 1)
if i\==10 then do /*────────────────────────────────convert # base I─►base ten.*/
_=0; p=0; do j=length(w) to 1 by -1 while w\==''
_= _ + (( pos( substr(w, j, 1), @)-1) * i**p); p=p+1
end /*j*/ /*increase power of base [↑]*/
w=_; p=1; _=0 /*[↓] convert fractional part*/
do j=1 for length(g)
_= _ + (( pos( substr(g, j, 1), @)-1)/i**p); p=p+1
end /*j*/ /*increase power of base [↑]*/
g= _
end
else if g\=='' then g= "."g /*reinsert period if needed. */
if t\==10 then do /*────────────────────────────────convert # base ten─►base T.*/
if w\=='' then do /*convert whole number part. */
do j=1 until t**j>w; end /*j*/
n=
do k=j-1 to 1 by -1; _= t**k
n=n || substr(!, 1 + w%_, 1); w= w // _
end /*k*/ /*remainder ≡ // */
w= n || substr(!, 1+w, 1)
end
if g\=='' then do; n= /*convert fractional part. */
do digits()+1 while g\==0; p= g*t; g= p//1
n= n || substr(!, 1 + p%1, 1)
end /*digits ···*/
if n==0 then n=
if n\=='' then n= '.'n /*only a fraction?*/
g= n
end
end
return oS || word( strip( space(w), 'L', 0)strip( strip(g, , 0), "T", .) 0, 1)
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error***: ' arg(1); say; exit 13</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 23.34375 &nbsp; 2 </tt>}}
<pre>
23.34375 (in base 10) = 10111.01011 (in base 2).
</pre>
'''{{out|output'''|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 1011.11101 &nbsp; 10 &nbsp; 2 </tt>}}
<pre>
1011.11101 (in base 2) = 11.90625 (in base 10).
</pre>
'''{{out|output'''|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> 3.14159265358979323846264338327950288419716939937510582097494 &nbsp; 62 </tt>}}
<pre>
3.14159265358979323846264338327950288419716939937510582097494 (in base 10) = 3.8mHUcirZ3g3aaX5Bn156eBkfOx43HPGx7xT3yBX1Aoh3TAAEolLiHWo8Z4XVLWesfA6 (in base 62).
</pre>
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 08.02.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 974 ⟶ 1,939:
If res<>soll Then
Say 'soll='soll
Return</langsyntaxhighlight>
'''Output:'''
<pre>23.34375 -> 10111.01011
Line 980 ⟶ 1,945:
-23.34375 -> -10111.01011
-1011.11101 -> -11.90625</pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
decimals(5)
 
numDec = 23.34375
convDecToBin(numDec)
 
numDig = 1011.11101
convBinToDec(numDig)
 
func convDecToBin(numd)
see "" + numd + " => "
num = numd - floor(numd)
 
a = floor(numd)
n = 0
while pow(2,n+1) < a
n = n + 1
end
for i = n to 0 step -1
x = pow(2,i)
if a >= x
see 1
a = a - x
else
see 0
ok
next
 
see "."
 
numbin = ""
 
for n = 1 to 5
bin = 1/(pow(2,n))
if num >= bin
numbin = numbin + "1"
num = num - bin
else
numbin = numbin + "0"
ok
next
 
see numbin
 
see nl
 
 
func convBinToDec(num)
 
see "" + num + " => "
 
numstr = string(num)
dot = substr(numstr,".")
num1 = substr(numstr,1,dot-1)
num2 = substr(numstr,dot+1,len(numstr)-dot)
 
numdec = 0
for n = 1 to len(num1)
if num1[n] = "1"
numdec = numdec + pow(2,len(num1)-n)
ok
next
 
numdig = 0
for n = 1 to len(num2)
if num2[n] = "1"
numdig = numdig + 1/pow(2,n)
ok
next
numdig = string(numdig)
numdig = substr(numdig,"0.","")
 
see "" + numdec + "." + numdig
</syntaxhighlight>
Output:
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
</pre>
 
=={{header|RPL}}==
{| class="wikitable"
! RPL code
! Comment
|-
|
SIGN LAST ABS
DUP BIN R→B →STR 3 OVER SIZE 1 - SUB
"." ROT FP
'''WHILE''' OVER SIZE 12 ≤ OVER AND '''REPEAT'''
2 * DUP IP →STR ROT SWAP +
SWAP FP
'''END''' DROP + STR→
*
≫ ‘<span style="color:blue">R→FB</span>’ STO
SIGN LAST ABS
DUP FP →STR SIZE 1 - SWAP
10 3 PICK ^ *
"#" SWAP →STR + →STR BIN B→R 2 ROT ^ / *
≫ ‘<span style="color:blue">FB→R</span>’ STO
|
<span style="color:blue">R→FB</span> ''( b10_real → b2_real ) ''
Memorize sign, use absolute value
Convert integer part to a binary string
Prepare stack for fractional part
loop until zero or decimal part size > 12
multiply by 2, take integer part as next decimal digit
keep fractional part
clean stack, add strings and convert back to floating point
restore sign
<span style="color:blue">FB→R</span> ''( b2_real → b10_real )''
Memorize sign, use absolute value
Get n = # of digits after the decimal point
Multiply input number by 10^n
Convert to base 10, divide by 2^n and restore sign
|}
23.34375 <span style="color:blue">R→FB</span>
1011.11101 <span style="color:blue">FB→R</span>
{{out}}
<pre>
2: 10111.01011
1: 11.90625
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def dec2bin(dec, precision=16) # String => String
int, df = dec.split(".")
minus = int.delete!("-")
Line 1,018 ⟶ 2,115:
dec2 = bin2dec(bin)
puts "%10s => %12s =>%10s" % [dec, bin, dec2]
end</langsyntaxhighlight>
 
{{out}}
Line 1,027 ⟶ 2,124:
-11.90625 => -1011.11101 => -11.90625
</pre>
 
=={{header|Scala}}==
===Idiomatic (FP with tailrec)===
<syntaxhighlight lang="scala">import java.lang.Long
 
import scala.annotation.tailrec
 
object DecimalFloatPoint2Binary extends App {
 
def doubleToBin(d: Double): String = {
require(d >= 0.0, "Only positive values are allowed.")
 
def fraction2BinaryFractionString(s: String, frac: Double) = {
@tailrec
def loop(acc: String, mid: Double): String = {
if (mid > 0.0) {
val r = mid * 2.0
if (r >= 1.0) loop(acc + "1", r - 1) else loop(acc + "0", r)
} else acc
}
 
loop(s + ".", frac)
}
 
val whole = math.floor(d).toLong
 
fraction2BinaryFractionString(Long.toString(whole, 2), d - whole)
}
 
def binToDec(s: String) = {
def num = Long.parseLong(s.replace(".", ""), 2)
 
def den = Long.parseLong("1" + s.split('.')(1).replace("1", "0"), 2)
 
num.toDouble / den
}
 
{ // main
println( { def d = 23.34375; s"$d\t => ${doubleToBin(d)}" } )
println( { def s = "1011.11101"; s"$s\t => ${binToDec(s)}" } )
}
}</syntaxhighlight>
{{Out}}Experience running it in your browser by [https://scastie.scala-lang.org/auzWgFqCRBaYoOaJV92tgw Scastie (remote JVM)].
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func dec2bin(String n) {
Num(Num(n, 10).base(2), 10)
}
Line 1,038 ⟶ 2,178:
 
with("23.34375") { |s| say (" #{s} => ", dec2bin(s)) }
with("1011.11101") { |s| say ( "#{s} => ", bin2dec(s)) }</langsyntaxhighlight>
{{out}}
<pre>
Line 1,048 ⟶ 2,188:
By far the easiest way to do this is to use Tcl's built-in handling of IEEE arithmetic, converting the IEEE representation into the string representation we want (and ''vice versa'') by simple string manipulations.
{{works with|Tcl|8.6}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
 
proc dec2bin x {
Line 1,105 ⟶ 2,245:
set d [bin2dec $b]
puts "$case => $b => $d"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,121 ⟶ 2,261:
</pre>
Adapting the code to work with IEEE double-precision floats is left as an exercise for the reader, as is dealing with the trickier special cases of the infinities and NaN.
 
=={{header|Wren}}==
{{trans|Go}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./fmt" for Conv, Fmt
 
var decToBin = Fn.new { |d|
var whole = d.truncate
var binary = Conv.itoa(whole, 2) + "."
var dd = d.fraction
while (dd > 0) {
var r = dd * 2
if (r >= 1) {
binary = binary + "1"
dd = r - 1
} else {
binary = binary + "0"
dd = r
}
}
return binary
}
 
var binToDec = Fn.new { |s|
var ss = s.replace(".", "")
var num = Conv.atoi(ss, 2)
ss = s.split(".")[1]
ss = ss.replace("1", "0")
var den = Conv.atoi("1" + ss, 2)
return num/den
}
 
var f = 23.34375
Fmt.print("$g\t => $s", f, decToBin.call(f))
var s = "1011.11101"
Fmt.print("$s\t => $g", s, binToDec.call(s))</syntaxhighlight>
 
{{out}}
<pre>
23.34375 => 10111.01011
1011.11101 => 11.90625
</pre>
 
=={{header|zkl}}==
Rather limited.
<langsyntaxhighlight lang="zkl">fcn bin2float(bstr){ // no exponents
bstr=bstr.strip();
m:=bstr[0,1]=="-"; if(m)bstr=bstr[1,*]; m=m and -1 or 1;
a,b:=bstr.split(".").apply(fcn(s){ s and s or 0 }).append(0,0);
(a.toInt(2).toFloat() + b.toInt(2).toFloat()/(2).pow(b.len()))*m
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach bstr in (T("1011.11101","0.01","0.11111111111","-.1","","1")){
println(bstr," --> ",bin2float(bstr).toString(20))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,142 ⟶ 2,324:
1 --> 1
</pre>
<langsyntaxhighlight lang="zkl">fcn float2bin(x,digitsOfPrecision=20){
m,zeros:="","0"*digitsOfPrecision;
if(x<0){ m="-"; x=-x }
Line 1,150 ⟶ 2,332:
if(z:=b.reverse().prefix(zeros)) b=b[0,-z]; // remove trailing zeros
String(m,a.toString(2),".",b);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">foreach x in (T(23.34375,(0.0).pi,-33.8,0.1,0.15625)){
println(x," --> ",s:=float2bin(x)," --> ",bin2float(s).toString(20));
}</langsyntaxhighlight>
{{out}}
<pre>
1,150

edits