Jump to content

[TOPIC: topicViewTemplate]
[GLOBAL: userSmallPhoto]
Photo

Formatting Decimal To 3 Places
Started by atrizhong Feb 15 2015 10:13 AM

- - - - -
4 replies to this topic
format string decimal round

Best Answer Rob Miracle , 15 February 2015 - 10:17 AM

string.format("%0.3f", value)

 

Rob

[TOPIC CONTROLS]
This topic has been archived. This means that you cannot reply to this topic.
[/TOPIC CONTROLS]
[modOptionsDropdown]
[/modOptionsDropdown]
[reputationFilter]
[TOPIC: post.html]
#1

atrizhong

[GLOBAL: userInfoPane.html]
atrizhong
  • Enthusiast

  • 95 posts
  • Corona SDK

Hello friends, quick question!

 

I need to format decimals to 3 places. How should I approach this?

 

For Example:

  • 0       ----> .000
  • .25    ----> .250
  • .1      ----> .100
  • .2983 ---> .298
  • .2986 ---> .299
  • 1       ----> 1.000

 

Thanks in advance!



[TOPIC: post.html]
#2

Rob Miracle

[GLOBAL: userInfoPane.html]
Rob Miracle
  • Moderator

  • 26,544 posts
  • Enterprise

  Best Answer

string.format("%0.3f", value)

 

Rob



[TOPIC: post.html]
#3

atrizhong

[GLOBAL: userInfoPane.html]
atrizhong
  • Enthusiast

  • 95 posts
  • Corona SDK

Thanks for the reply!

 

 

Right now, I have this code, which works

local avg = string.format("%.3f",player.AVG)

if(string.sub(avg, 1,1) == "0") then --Remove leading 0, if any
    avg = string.sub(avg, 2)
end

But it seems a little complicated and messy.

 

Is there any way to get rid of the leading 0 too, only using string.format()?


Edited by atrizhong, 15 February 2015 - 11:17 AM.


[TOPIC: post.html]
#4

Rob Miracle

[GLOBAL: userInfoPane.html]
Rob Miracle
  • Moderator

  • 26,544 posts
  • Enterprise

Technically speaking, numbers smaller than 1, should have a 0. in front of it.  There isn't an format I know of that won't try and put a 0 there.  You're way of removing it is probably the best way.

 

Rob



[TOPIC: post.html]
#5

atrizhong

[GLOBAL: userInfoPane.html]
atrizhong
  • Enthusiast

  • 95 posts
  • Corona SDK

You're right that 0s should usually be in front of numbers less than one, but in baseball statistics, the 0 is usually omitted!

 

http://espn.go.com/mlb/statistics




[topic_controls]
[/topic_controls]