lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


> Correctness has its price. 8-/

Sure. Here's a simple but perhaps not too expensive solution:

function xtostring(x)
	local s,y
	local f=string.format
	s=f("%.14g",x) y=tonumber(s) if y==x then return s,14 end
	s=f("%.15g",x) y=tonumber(s) if y==x then return s,15 end
	s=f("%.16g",x) y=tonumber(s) if y==x then return s,16 end
	s=f("%.17g",x) y=tonumber(s) if y==x then return s,17 end
	assert(false)
end

function test(x)
	print(x,xtostring(x))
end

test(0.1)
test(0.1+0.2)
test((0.1+0.2)+0.3)
test(0.1+(0.2+0.3))
test(0.1+0.2+0.3)

whose output is

0.1	0.1	14
0.3	0.30000000000000004	17
0.6	0.6000000000000001	16
0.6	0.6	14
0.6	0.6000000000000001	16