Removing decimal places from a 'float' without rounding - example

Help creating logic scripts for Air Manager Instruments

Moderators: russ, Ralph

Message
Author
User avatar
jph
Posts: 2856
Joined: Fri Apr 10, 2020 12:50 pm
Location: Somewhere over the rainbow..

Removing decimal places from a 'float' without rounding - example

#1 Post by jph »

More of a series of LUA functions that I have needed so had to create, and finally got around to it. Here i share my offering

Problem -
I wanted a function to strip decimal places from a float but to absolutely NOT round (either up or down) the result and just remove the unwanted decimal places. Basically 'truncate' the number of decimal places of a float without altering the original format or values of the individual decimal places.

I came up with various solutions but this is my choice to use.
The detailed explanation is longer than the simple function :)


Solution -

Code: Select all

-- A function to return a limited number of decimal places WITHOUT !!!   rounding
-- an example by Joe Hanley (JPH) 2022

function stripDecimalPlaces(num, numDecimalPlaces)
  local factor = 10^(numDecimalPlaces)
  return math.floor(num * factor) / factor
end
-- ...........................................................................................................................

-- Thats it. The above is the complete funtion.
-- Here are some examples of appropriate function calls.

-- This returns 1.23 for the number 1.2311 with 2 decimal places

local nonRoundedFormat = stripDecimalPlaces(1.23111, 2)
print (nonRoundedFormat)

-- This returns 1.23 for the number 1.23999 with 2 decimal places

local nonRoundedFormat = stripDecimalPlaces(1.23999, 2)
print (nonRoundedFormat)

--[[
How does it operate ?
Ok. .....

The function takes a number and a desired number of decimal places as input and returns a new number with the same value as the original 
number, but with a limited number of decimal places. The function does this by first multiplying the input number by 10 raised to the power 
of the desired number of decimal places. This has the effect of shifting the decimal point to the right by the desired number of places. 
For example, if the input number is 1.23111 and the desired number of decimal places is 2, 
the result of 1.23111 * 10^2 is 123.111
Next, the function takes the result of this multiplication and applies the math.floor function to it. 
This function rounds the number down to the nearest integer. So, in the example above, the result of math.floor(123.111) would be 123.

Finally, the function divides the result of the math.floor function by the same factor that was used in the first step 
10 raised to the power of the desired number of decimal places). This has the effect of shifting the decimal point back to its original position, 
but with a limited number of decimal places. So, in the example above, the final result of the function would be 1.23.
The function does not perform any rounding, so it will simply truncate any decimal places beyond the desired number of decimal places. 
For example, if the input number is 1.23999 and the desired number of decimal places is 2, the function will return 1.23, 
rather than rounding the number up to 1.24.

The function is called with two arguments: the input number and the desired number of decimal places. 
The function first defines a local variable factor which is equal to 10 raised to the power of the desired number of decimal places. 
It then returns the result of the input number multiplied by factor, passed through the math.floor function, and then divided by factor again. 
The final result is the input number with a limited number of decimal places, without any rounding. --]]
Hope someone finds it useful or informative.
Joe
Joe. CISSP, MSc.

SimPassion
Posts: 5340
Joined: Thu Jul 27, 2017 12:22 am

Re: Removing decimal places from a 'float' without rounding - example

#2 Post by SimPassion »

Nice done Joe, if it's a matter to get the whole part of float, without fract, I've also made it at some point, in another way and saved in my snippets
All right we have to take in account the decimal point, in this way your solution is more elegant

Code: Select all

------------------------------
-- STRING Extract (here from left, start with index 1, not with 0)
------------------------------

function pr_str_lftextract(str,nb)
	strlen = string.len(str)
	if strlen < nb then nb = strlen end
	return str:sub(1,nb)
end

number = 3.9871

result = pr_str_lftextract(tostring(number),1)
print(result)

-- --> give 3

result = pr_str_lftextract(tostring(number),4)
print(result)

-- --> give 3.98


Here's some more idea in other area, including already existing Sim Innovations lib at the end, in order to not miss what they already build :

Code: Select all

--====================================================================================
--								REFERENCE PURPOSE
--====================================================================================

------------------------------
-- ARRAYS
------------------------------

    mt = {}          -- create the matrix
    N = 10
    M = 12
    for i=1,N do
      mt[i] = {}     -- create a new row
      for j=1,M do
        mt[i][j] = 0
      end
    end

------------------------------
-- STRING Extract (here from left, start with index 1, not with 0)
------------------------------

function pr_str_lftextract(str,nb)
	strlen = string.len(str)
	if strlen < nb then nb = strlen end
	return str:sub(1,nb)
end

number = 3.9871
result = pr_str_lftextract(tostring(number),4)
print(result)

-- --> give 3.98

------------------------------
-- IF	if then else elseif
------------------------------

	-- Typical way
	value = 12
	if value > 2 then
		visible(txt_id, true)
	else
		visible(txt_id, false)
	end

	-- Inline
	visible(txt_id, value > 2)

------------------------------
-- SWITCH (SELECT CASE like)
------------------------------

-- sample 1

	local a = 2
	local switch = {
		[1] = function()print "Case 1."end,
		[2] = function()print "Case 2."end,
		[3] = function()print "Case 3."end
	}

	local f = switch[a]
	if(f) then
		f()
	else
		print "Case default."
	end

local chann_on = {
	["A"] = function() txt_style(str_channelA,txt_style5) end,
	["B"] = function() txt_style(str_channelB,txt_style5) end,
	["C"] = function() txt_style(str_channelC,txt_style5) end,
	["D"] = function() txt_style(str_channelD,txt_style5) end,
	["E"] = function() txt_style(str_channelE,txt_style5) end,
	["F"] = function() txt_style(str_channelF,txt_style5) end,
	["G"] = function() txt_style(str_channelG,txt_style5) end,
	["H"] = function() txt_style(str_channelH,txt_style5) end,
	["I"] = function() txt_style(str_channelI,txt_style5) end,
	["J"] = function() txt_style(str_channelJ,txt_style5) end,
	["K"] = function() txt_style(str_channelK,txt_style5) end,
	["L"] = function() txt_style(str_channelL,txt_style5) end,
	["M"] = function() txt_style(str_channelM,txt_style5) end,
	["N"] = function() txt_style(str_channelN,txt_style5) end,
	["O"] = function() txt_style(str_channelO,txt_style5) end,
	["P"] = function() txt_style(str_channelP,txt_style5) end
}

local btn_pr = {
	[1] = function()  end,
	[2] = function()  end,
	[3] = function()  end,
	[4] = function()  end,
	[5] = function()  end,
	[6] = function()  end,
	[7] = function()  end,
	[8] = function()  end,
	[9] = function()  end,
	[10] = function()  end,
	[11] = function()  end,
	[12] = function()  end,
	[13] = function()  end,
	[14] = function()  end,
	[15] = function()  end,
	[16] = function()  end
}

function pr_arr_press_capt(row, col)
	-- print("CAPT button pressed at row " .. row .. ", col " .. col)

	btn_nbr = (col+1)+(row*4)

	local f_exec_btn_pr = btn_pr[btn_nbr]
	if (f_exec_btn_pr) then
		f_exec_btn_pr()
	else
	end
	
	print("CAPT PRESS Multiply : "..(col+1)+(row*4))
end

------------------------------
-- FORMAT string.format
------------------------------

	my_txt = string.format("First number is %d, second is %d", 123, 999)

	my_number = 100.123

	-- Prints 'Number = 100.123'
	print(string.format("Number = %f", my_number))

	-- Prints 'Number = 00000100' (8 characters total, 0 fractional characters)
	print(string.format("Number = %08.0f", my_number))

	-- Prints 'Number = 00100.12' (8 characters total, 2 fractional characters)
	print(string.format("Number = %08.2f", my_number))

	-- Prints 'Number = 100.1230' (8 characters total, 4 fractional characters)
	print(string.format("Number = %08.4f", my_number))

-- Argument 			Type 			Code 									Result
-- %s 					String 			string.format("Name = %s", "Jack") 		"Name = Jack"
-- %d 					Integer 		string.format("Number = %d", 123) 		"Number = 123"
-- %f 					Float & Double 	string.format("Number = %f", 12.45) 	"Number = 12.45"
-- %c 					Character 		string.format("Char = %c", 65) 			"Char = A" (65 corresponds to the letter 'A' in the ASCII table)
-- %s 					Boolean 		string.format("Value = %s", true) 		"Value = true" 

	-- Returns 15
	my_value = var_cap(15, 10, 20)

	-- Returns 1.1
	my_value = var_round(1.12345, 1)

	-- Returns 1.20
	my_value = var_format(1.2, 2)


------------------------------
-- FOR LOOP
------------------------------

	for i = 10,1,-1
	do
		print(i)
	end

------------------------------
-- EVENT CALLBACK
------------------------------

function event_callback(event)	-- [STARTED / SHOWING / CLOSING / FLIGHT_SIM_CHANGED]
    if event == "CLOSING" then
		hw_led_set(hw_led_fda,0)
		hw_led_set(hw_led_fdb,0)
		hw_led_set(hw_led_atarm,0)
		hw_led_set(hw_led_n1,0)
		hw_led_set(hw_led_speed,0)
		hw_led_set(hw_led_vnav,0)
		hw_led_set(hw_led_lvlchg,0)
		hw_led_set(hw_led_hdgsel,0)
		hw_led_set(hw_led_lnav,0)
		hw_led_set(hw_led_vorloc,0)
		hw_led_set(hw_led_app,0)
		hw_led_set(hw_led_althld,0)
		hw_led_set(hw_led_vs,0)
		hw_led_set(hw_led_cmda,0)
		hw_led_set(hw_led_cmdb,0)
		hw_led_set(hw_led_cwsa,0)
		hw_led_set(hw_led_cwsb,0)
		hw_chr_display_set_text(display_chr_id, 0, 0, "        ")
		hw_chr_display_set_text(display_chr_id, 1, 0, "        ")
    end
end

event_subscribe(event_callback)

-- SIM INNOVATIONS Lua Functions Lib
-------------------------------------

-- Rounds a number to the given number of decimal places...
-- example: var_round(5.46,1) becomes '5.5'
function var_round(val, decimal)
	if (decimal) then
		return math.floor((val * 10^decimal) + 0.5) / (10^decimal)
	else
		return math.floor(val+0.5)
	end
end

function var_format(val, decimals)

  local u = 0
  local dec = 0
  
  if val > 0 then
    u = math.floor(val)
  end
  if val < 0 then
    u = math.ceil(val)
  end
  
  if val > 0 then
    dec = (val - u) * (10^decimals)
  end
  
  if val < 0 then
    dec = (u - val) * (10^decimals)
  end
  
  if decimals == 0 then
    return string.format("%.0f", u)
  elseif val > -1 and val < 0 then
    return string.format("-%.0f.%0" .. tostring(decimals) .. ".0f", math.floor(u), math.floor(dec))
  else
	return string.format("%.0f.%0" .. tostring(decimals) .. ".0f", math.floor(u), math.floor(dec))
  end
end

-- Caps a number to the given minimum and maximum
function var_cap(val, minimum, maximum)
	if val < minimum then
		return minimum
	end
	if val > maximum then
		return maximum
	end
	
	return val
end

function fif(condition, if_true, if_false)
  if condition then return if_true else return if_false end
end

User avatar
jph
Posts: 2856
Joined: Fri Apr 10, 2020 12:50 pm
Location: Somewhere over the rainbow..

Re: Removing decimal places from a 'float' without rounding - example

#3 Post by jph »

Thanks Gilles, :D
Excellent. That is great stuff to add and enhance. Thank you, It is so interesting to see people's solutions to seemingly simple issues (at first glance)
Nice one,
Joe
Joe. CISSP, MSc.

User avatar
Keith Baxter
Posts: 4685
Joined: Wed Dec 20, 2017 11:00 am
Location: Botswana

Re: Removing decimal places from a 'float' without rounding - example

#4 Post by Keith Baxter »

Hi,

I just use string.sub() and can extract any set of data within the string. It is a standard lua function.

Code: Select all

my_number = 123.987654321
my_number=string.sub(my_number,1,2)
print(my_number)

my_number = 123.987654321
my_number=string.sub(my_number,1,5)
print(my_number)

my_number = 123.987654321
my_number=string.sub(my_number,3,-5)
print(my_number)

my_number = 123.987654321
my_number=string.sub(my_number,-10,-5)
print(my_number)


--Now lets format this to a fixed number of decimals (5) Note how a 8 digit set to be used for char displays is simplified.
my_number = 12.987654321
my_number =string.format("% 9.5f",string.sub(my_number,1,9))
print(my_number)

--You need to be careful though. There is a difference between these two The first one forces a whitespace
my_number = 123.987654321
my_number =string.format("% 9.5f",string.sub(my_number,1,9))
print(my_number)

my_number = 123.987654321
my_number =string.format("%9.5f",string.sub(my_number,1,9))
print(my_number)
Keith
Last edited by Keith Baxter on Sun Dec 18, 2022 7:29 pm, edited 3 times in total.
AMD RYZEN 9 5950X CPU, Corsair H80I cooler, ASUS TUF GAMING B550-PLUS AMD Ryzen Mother Board,  32Gb ram Corsair Vengeance 3000Mh, MSI GTX960 4G graphics card 

SimPassion
Posts: 5340
Joined: Thu Jul 27, 2017 12:22 am

Re: Removing decimal places from a 'float' without rounding - example

#5 Post by SimPassion »

Yes Keith, str:sub (where "str" is only a variable name here) and string.sub are equivalent and allow the same result

[EDIT] Typo and precision added
Last edited by SimPassion on Sun Dec 18, 2022 8:32 pm, edited 1 time in total.

User avatar
Keith Baxter
Posts: 4685
Joined: Wed Dec 20, 2017 11:00 am
Location: Botswana

Re: Removing decimal places from a 'float' without rounding - example

#6 Post by Keith Baxter »

SimPassion wrote: Sun Dec 18, 2022 7:17 pm Yes Keith, str:sub and string.sub are equivalent and allow the same ressult
Gilles,

Yes I was not sure if I was missing something.

Ok yes you could also do this one liner

Code: Select all

my_number = 123.987654321
my_number=string.sub(my_number * 10^10,1,12)
print(my_number)

my_number = 123.987654321
my_number=string.sub(my_number * 10^10,1,6)
print(my_number)
Keith
AMD RYZEN 9 5950X CPU, Corsair H80I cooler, ASUS TUF GAMING B550-PLUS AMD Ryzen Mother Board,  32Gb ram Corsair Vengeance 3000Mh, MSI GTX960 4G graphics card 

User avatar
jph
Posts: 2856
Joined: Fri Apr 10, 2020 12:50 pm
Location: Somewhere over the rainbow..

Re: Removing decimal places from a 'float' without rounding - example

#7 Post by jph »

Hi Gilles,
Another method for finding just the integer (or the integer AND the fractional) is as follows. (can be used 2 ways as described)

Code: Select all


local number = 3.14
local integer,fractional = math.modf(number) -- integer will be 3, fractional will be 0.14

print (integer)
print (fractional)
-- result = 3
-- result = 0.14


--[[
However, you can pass, in this case just the 'integer' only and the return will be purely the integer part of the number 
As in the following which acts as a means of obtaining only the integer of the passed float argument
--]]

local number = 193.087654
local integer = math.modf(number) 
print (integer)

--result = 193
Lua really is powerful and a pain at the same time :lol: It is good to see differing options.
It is a nice language.
Joe
Joe. CISSP, MSc.

User avatar
jph
Posts: 2856
Joined: Fri Apr 10, 2020 12:50 pm
Location: Somewhere over the rainbow..

Re: Removing decimal places from a 'float' without rounding - example

#8 Post by jph »

Keith Baxter wrote: Sun Dec 18, 2022 6:49 pm Hi,

I just use string.sub() and can extract any set of data within the string. It is a standard lua function.

Code: Select all

my_number = 123.987654321
my_number=string.sub(my_number,1,2)
print(my_number)
Hi,
whilst that is ok and works you are using string conversions as opposed to pure numbers which may sometimes cause issue later.
If you only ever stick to LUA 5.4 then you would usually be absolutely fine because if you attempt to perform arithmetic operations on strings that contain numbers, the interpreter will automatically attempt to convert the strings to numbers before performing the operation. This is known as "string coercion."
However, it is generally a good idea to be explicit about the data types you are working with and to use the appropriate functions to convert between different data types when necessary. This can make your code more readable and easier to understand, and it can help prevent errors that may occur if the data types of your variables change unexpectedly. If you ever want to code in different languages you may find this not to be an advantage. Absolutely not a criticism, but an observation.
As you are unlikely to use a different language it is all good. If I was writing this routine for use in both Arduino, for example, and also in Lua then it may be different.
Still nice work though.
Joe
Joe. CISSP, MSc.

User avatar
jph
Posts: 2856
Joined: Fri Apr 10, 2020 12:50 pm
Location: Somewhere over the rainbow..

Re: Removing decimal places from a 'float' without rounding - example

#9 Post by jph »

SimPassion wrote: Sun Dec 18, 2022 12:46 pm Nice done Joe, if it's a matter to get the whole part of float, without fract, I've also made it at some point, in another way and saved in my snippets
All right we have to take in account the decimal point, in this way your solution is more elegant

Code: Select all

------------------------------
-- STRING Extract (here from left, start with index 1, not with 0)
------------------------------

function pr_str_lftextract(str,nb)
	strlen = string.len(str)
	if strlen < nb then nb = strlen end
	return str:sub(1,nb)
end

number = 3.9871

result = pr_str_lftextract(tostring(number),1)
print(result)

-- --> give 3

result = pr_str_lftextract(tostring(number),4)
print(result)

-- --> give 3.98



Here's some more idea in other area, including already existing Sim Innovations lib at the end, in order to not miss what they already build :

Code: Select all

--====================================================================================
--								REFERENCE PURPOSE
--====================================================================================

------------------------------
-- ARRAYS
------------------------------

    mt = {}          -- create the matrix
    N = 10
    M = 12
    for i=1,N do
      mt[i] = {}     -- create a new row
      for j=1,M do
        mt[i][j] = 0
      end
    end

------------------------------
-- STRING Extract (here from left, start with index 1, not with 0)
------------------------------

function pr_str_lftextract(str,nb)
	strlen = string.len(str)
	if strlen < nb then nb = strlen end
	return str:sub(1,nb)
end

number = 3.9871
result = pr_str_lftextract(tostring(number),4)
print(result)

-- --> give 3.98

------------------------------
-- IF	if then else elseif
------------------------------

	-- Typical way
	value = 12
	if value > 2 then
		visible(txt_id, true)
	else
		visible(txt_id, false)
	end

	-- Inline
	visible(txt_id, value > 2)

------------------------------
-- SWITCH (SELECT CASE like)
------------------------------

-- sample 1

	local a = 2
	local switch = {
		[1] = function()print "Case 1."end,
		[2] = function()print "Case 2."end,
		[3] = function()print "Case 3."end
	}

	local f = switch[a]
	if(f) then
		f()
	else
		print "Case default."
	end

local chann_on = {
	["A"] = function() txt_style(str_channelA,txt_style5) end,
	["B"] = function() txt_style(str_channelB,txt_style5) end,
	["C"] = function() txt_style(str_channelC,txt_style5) end,
	["D"] = function() txt_style(str_channelD,txt_style5) end,
	["E"] = function() txt_style(str_channelE,txt_style5) end,
	["F"] = function() txt_style(str_channelF,txt_style5) end,
	["G"] = function() txt_style(str_channelG,txt_style5) end,
	["H"] = function() txt_style(str_channelH,txt_style5) end,
	["I"] = function() txt_style(str_channelI,txt_style5) end,
	["J"] = function() txt_style(str_channelJ,txt_style5) end,
	["K"] = function() txt_style(str_channelK,txt_style5) end,
	["L"] = function() txt_style(str_channelL,txt_style5) end,
	["M"] = function() txt_style(str_channelM,txt_style5) end,
	["N"] = function() txt_style(str_channelN,txt_style5) end,
	["O"] = function() txt_style(str_channelO,txt_style5) end,
	["P"] = function() txt_style(str_channelP,txt_style5) end
}

local btn_pr = {
	[1] = function()  end,
	[2] = function()  end,
	[3] = function()  end,
	[4] = function()  end,
	[5] = function()  end,
	[6] = function()  end,
	[7] = function()  end,
	[8] = function()  end,
	[9] = function()  end,
	[10] = function()  end,
	[11] = function()  end,
	[12] = function()  end,
	[13] = function()  end,
	[14] = function()  end,
	[15] = function()  end,
	[16] = function()  end
}

function pr_arr_press_capt(row, col)
	-- print("CAPT button pressed at row " .. row .. ", col " .. col)

	btn_nbr = (col+1)+(row*4)

	local f_exec_btn_pr = btn_pr[btn_nbr]
	if (f_exec_btn_pr) then
		f_exec_btn_pr()
	else
	end
	
	print("CAPT PRESS Multiply : "..(col+1)+(row*4))
end

------------------------------
-- FORMAT string.format
------------------------------

	my_txt = string.format("First number is %d, second is %d", 123, 999)

	my_number = 100.123

	-- Prints 'Number = 100.123'
	print(string.format("Number = %f", my_number))

	-- Prints 'Number = 00000100' (8 characters total, 0 fractional characters)
	print(string.format("Number = %08.0f", my_number))

	-- Prints 'Number = 00100.12' (8 characters total, 2 fractional characters)
	print(string.format("Number = %08.2f", my_number))

	-- Prints 'Number = 100.1230' (8 characters total, 4 fractional characters)
	print(string.format("Number = %08.4f", my_number))

-- Argument 			Type 			Code 									Result
-- %s 					String 			string.format("Name = %s", "Jack") 		"Name = Jack"
-- %d 					Integer 		string.format("Number = %d", 123) 		"Number = 123"
-- %f 					Float & Double 	string.format("Number = %f", 12.45) 	"Number = 12.45"
-- %c 					Character 		string.format("Char = %c", 65) 			"Char = A" (65 corresponds to the letter 'A' in the ASCII table)
-- %s 					Boolean 		string.format("Value = %s", true) 		"Value = true" 

	-- Returns 15
	my_value = var_cap(15, 10, 20)

	-- Returns 1.1
	my_value = var_round(1.12345, 1)

	-- Returns 1.20
	my_value = var_format(1.2, 2)


------------------------------
-- FOR LOOP
------------------------------

	for i = 10,1,-1
	do
		print(i)
	end

------------------------------
-- EVENT CALLBACK
------------------------------

function event_callback(event)	-- [STARTED / SHOWING / CLOSING / FLIGHT_SIM_CHANGED]
    if event == "CLOSING" then
		hw_led_set(hw_led_fda,0)
		hw_led_set(hw_led_fdb,0)
		hw_led_set(hw_led_atarm,0)
		hw_led_set(hw_led_n1,0)
		hw_led_set(hw_led_speed,0)
		hw_led_set(hw_led_vnav,0)
		hw_led_set(hw_led_lvlchg,0)
		hw_led_set(hw_led_hdgsel,0)
		hw_led_set(hw_led_lnav,0)
		hw_led_set(hw_led_vorloc,0)
		hw_led_set(hw_led_app,0)
		hw_led_set(hw_led_althld,0)
		hw_led_set(hw_led_vs,0)
		hw_led_set(hw_led_cmda,0)
		hw_led_set(hw_led_cmdb,0)
		hw_led_set(hw_led_cwsa,0)
		hw_led_set(hw_led_cwsb,0)
		hw_chr_display_set_text(display_chr_id, 0, 0, "        ")
		hw_chr_display_set_text(display_chr_id, 1, 0, "        ")
    end
end

event_subscribe(event_callback)

-- SIM INNOVATIONS Lua Functions Lib
-------------------------------------

-- Rounds a number to the given number of decimal places...
-- example: var_round(5.46,1) becomes '5.5'
function var_round(val, decimal)
	if (decimal) then
		return math.floor((val * 10^decimal) + 0.5) / (10^decimal)
	else
		return math.floor(val+0.5)
	end
end

function var_format(val, decimals)

  local u = 0
  local dec = 0
  
  if val > 0 then
    u = math.floor(val)
  end
  if val < 0 then
    u = math.ceil(val)
  end
  
  if val > 0 then
    dec = (val - u) * (10^decimals)
  end
  
  if val < 0 then
    dec = (u - val) * (10^decimals)
  end
  
  if decimals == 0 then
    return string.format("%.0f", u)
  elseif val > -1 and val < 0 then
    return string.format("-%.0f.%0" .. tostring(decimals) .. ".0f", math.floor(u), math.floor(dec))
  else
	return string.format("%.0f.%0" .. tostring(decimals) .. ".0f", math.floor(u), math.floor(dec))
  end
end

-- Caps a number to the given minimum and maximum
function var_cap(val, minimum, maximum)
	if val < minimum then
		return minimum
	end
	if val > maximum then
		return maximum
	end
	
	return val
end

function fif(condition, if_true, if_false)
  if condition then return if_true else return if_false end
end
I like the presentation GIlles :D I am not too concerned with the specific 'helpers' that SI provides as they can, imho, confuse things. I do like the presentation of the string,format though. Appreciated.

It mostly follows the convention - Nice :mrgreen:

Code: Select all

--[[The format_string is a string that specifies how the arguments should be formatted. It can include format specifiers, 
which are placeholders for the arguments. The format specifiers start with the "%" character and are followed by a letter that 
specifies the type of the argument (e.g., "d" for integers, "s" for strings).

Here is a list of the most commonly used format specifiers in Lua 5.4: --]]

%s: formats the argument as a string
%d: formats the argument as an integer
%f: formats the argument as a floating-point value
%g: formats the argument in either fixed-point or scientific notation, whichever is shorter
%e: formats the argument in scientific notation
--[[

You can also specify the width, precision, and alignment of the formatted string by using additional characters after the % symbol. 
For example, %10.2f would format the argument as a floating-point value with a width of 10 characters and a precision of 2 decimal places, 
and %-10s would format the argument as a 
left-aligned string with a width of 10 characters--]]
.
Joe. CISSP, MSc.

SimPassion
Posts: 5340
Joined: Thu Jul 27, 2017 12:22 am

Re: Removing decimal places from a 'float' without rounding - example

#10 Post by SimPassion »

jph wrote: Mon Dec 19, 2022 9:29 am Hi Gilles,
Another method for finding just the integer (or the integer AND the fractional) is as follows. (can be used 2 ways as described)

Code: Select all


local number = 3.14
local integer,fractional = math.modf(number) -- integer will be 3, fractional will be 0.14

print (integer)
print (fractional)
-- result = 3
-- result = 0.14


--[[
However, you can pass, in this case just the 'integer' only and the return will be purely the integer part of the number 
As in the following which acts as a means of obtaining only the integer of the passed float argument
--]]

local number = 193.087654
local integer = math.modf(number) 
print (integer)

--result = 193
Lua really is powerful and a pain at the same time :lol: It is good to see differing options.
It is a nice language.
Joe
This one is nice and concise, I like it, good find Joe

Post Reply