Message Boards Message Boards

0
|
5272 Views
|
7 Replies
|
1 Total Likes
View groups...
Share
Share this post:

Round an integer to the two leading digits with trailing zeroes?

Posted 5 years ago

56789012 -> 57000000, for example. Thanks for any help.

POSTED BY: Richard Jensen
7 Replies

Rounding to arbitrary leading digits. Not the most elegant solution but does the trick

In[1]:= leadRound[n_, l_ : 2] := 
 Round[n, 10^(Length[IntegerDigits[n]] - l)]

In[2]:= leadRound[56789012]
leadRound[56789012, 2]
leadRound[56789012, 3]
leadRound[56789012, 5]

Out[2]= 57000000

Out[3]= 57000000

Out[4]= 56800000

Out[5]= 56789000

In[6]:= leadRound[56789012, 12]

Out[6]= 56789012
POSTED BY: Martijn Froeling
Posted 5 years ago

Very helpful. Thank you, gentlemen.

POSTED BY: Richard Jensen
Posted 5 years ago

Frank, you are right. The second argument of Round "out of the box" starts from the decimal point. But the OP wants a rounding starting from the leading digit. Which your function does.

POSTED BY: Hans Milton

The second argument depends on the size of the number being rounded.

POSTED BY: Frank Kampas
Posted 5 years ago

The function Round could be used right out of the box. Documentation.

In[1]:= Round[56789012, 10^6]
Out[1]= 57000000
POSTED BY: Hans Milton
In[1]:= rnd[n_] := Round[n, 10^(Floor[Log[10, n]] - 1)]

In[2]:= rnd[56789012]

Out[2]= 57000000
POSTED BY: Frank Kampas
rnd[n_] := Block[{d = 10^(Floor[Log[10, n]] - 1)}, d*Round[n/d]]

rnd[56789012]

57000000
POSTED BY: Frank Kampas
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract